From d631267548fdcc8eee3a4d909e0ebc2c0de59d17 Mon Sep 17 00:00:00 2001
From: Giuliano Zaro <3684609+GMagician@users.noreply.github.com>
Date: Tue, 13 Nov 2018 11:31:58 +0100
Subject: [PATCH] Refine endstops fixes (#12413)

When endstops/probe are enabled `ENDSTOP_NOISE_THRESHOLD` calls to `update` are required to properly re-sync endstops/probe status.
---
 Marlin/src/module/endstops.cpp | 25 ++++++++++++++++++-------
 Marlin/src/module/endstops.h   |  2 ++
 2 files changed, 20 insertions(+), 7 deletions(-)

diff --git a/Marlin/src/module/endstops.cpp b/Marlin/src/module/endstops.cpp
index 1e2d805b6e..221783e211 100644
--- a/Marlin/src/module/endstops.cpp
+++ b/Marlin/src/module/endstops.cpp
@@ -42,7 +42,7 @@
 
 Endstops endstops;
 
-// public:
+// private:
 
 bool Endstops::enabled, Endstops::enabled_globally; // Initialized by settings.load()
 volatile uint8_t Endstops::hit_state;
@@ -259,15 +259,13 @@ void Endstops::poll() {
 
 void Endstops::enable_globally(const bool onoff) {
   enabled_globally = enabled = onoff;
-
-  update();
+  resync();
 }
 
 // Enable / disable endstop checking
 void Endstops::enable(const bool onoff) {
   enabled = onoff;
-
-  update();
+  resync();
 }
 
 // Disable / Enable endstops based on ENSTOPS_ONLY_FOR_HOMING and global enable
@@ -287,11 +285,24 @@ void Endstops::not_homing() {
 #if HAS_BED_PROBE
   void Endstops::enable_z_probe(const bool onoff) {
     z_probe_enabled = onoff;
-
-    update();
+    resync();
   }
 #endif
 
+// Get the stable endstop states when enabled
+void Endstops::resync() {
+  if (!abort_enabled()) return;     // If endstops/probes are disabled the loop below can hang
+
+  #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE) && !ENDSTOP_NOISE_THRESHOLD
+    update();
+  #else
+    safe_delay(2);  // Wait for Temperature ISR (runs at 1KHz)
+  #endif
+  #if ENDSTOP_NOISE_THRESHOLD
+    while (endstop_poll_count) safe_delay(1);
+  #endif
+}
+
 #if ENABLED(PINS_DEBUGGING)
   void Endstops::run_monitor() {
     if (!monitor_flag) return;
diff --git a/Marlin/src/module/endstops.h b/Marlin/src/module/endstops.h
index f73c17946f..7892ea81da 100644
--- a/Marlin/src/module/endstops.h
+++ b/Marlin/src/module/endstops.h
@@ -162,6 +162,8 @@ class Endstops {
       static void enable_z_probe(const bool onoff=true);
     #endif
 
+    static void resync();
+
     // Debugging of endstops
     #if ENABLED(PINS_DEBUGGING)
       static bool monitor_flag;
-- 
GitLab