From a8cf2909f79105bfafce207cd3b914e63f5c8545 Mon Sep 17 00:00:00 2001
From: Fredrik Andersson <fredrikandersson@mac.com>
Date: Mon, 21 Mar 2022 02:14:45 +0100
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Encoder=20button=20noise=20filter?=
 =?UTF-8?q?=20(#23925)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 Marlin/src/lcd/marlinui.h | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/Marlin/src/lcd/marlinui.h b/Marlin/src/lcd/marlinui.h
index 83eb332105d..b28687ee917 100644
--- a/Marlin/src/lcd/marlinui.h
+++ b/Marlin/src/lcd/marlinui.h
@@ -680,7 +680,31 @@ public:
     #endif
 
     static void update_buttons();
-    static bool button_pressed() { return BUTTON_CLICK() || TERN(TOUCH_SCREEN, touch_pressed(), false); }
+
+    #if HAS_ENCODER_NOISE
+      #ifndef ENCODER_SAMPLES
+        #define ENCODER_SAMPLES 10
+      #endif
+
+      /**
+       * Some printers may have issues with EMI noise especially using a motherboard with 3.3V logic levels
+       * it may cause the logical LOW to float into the undefined region and register as a logical HIGH
+       * causing it to errorenously register as if someone clicked the button and in worst case make the printer
+       * unusable in practice.
+       */
+      static bool hw_button_pressed() {
+        LOOP_L_N(s, ENCODER_SAMPLES) {
+          if (!BUTTON_CLICK()) return false;
+          safe_delay(1);
+        }
+        return true;
+      }
+    #else
+      static bool hw_button_pressed() { return BUTTON_CLICK(); }
+    #endif
+
+    static bool button_pressed() { return hw_button_pressed() || TERN0(TOUCH_SCREEN, touch_pressed()); }
+
     #if EITHER(AUTO_BED_LEVELING_UBL, G26_MESH_VALIDATION)
       static void wait_for_release();
     #endif