From 41c88929fb6fa4fd3ed61c9161a08bc9e7c2bc88 Mon Sep 17 00:00:00 2001 From: David Buezas Date: Wed, 13 Mar 2024 22:49:16 +0100 Subject: [PATCH] Counter based debouncing --- Marlin/src/lcd/marlinui.cpp | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/Marlin/src/lcd/marlinui.cpp b/Marlin/src/lcd/marlinui.cpp index 1f83342cc7bd4..a324228c3dc13 100644 --- a/Marlin/src/lcd/marlinui.cpp +++ b/Marlin/src/lcd/marlinui.cpp @@ -1389,7 +1389,10 @@ void MarlinUI::init() { #if MARLINUI_ENCODER_DELTA #define ENCODER_DEBOUNCE_MS 2 - + #ifdef ENCODER_DEBOUNCE_MS + // #define USE_TIME_BLOCKING_DEBOUNCING + #define USE_COUNTER_DEBOUNCING + #endif /** * Get the encoder delta (-2 -1 0 +1 +2) since the last call, reading the live encoder state. * Pins may be debounced to filter noise. @@ -1400,7 +1403,33 @@ void MarlinUI::init() { const enc_t live_enc = { BUTTON_PRESSED(EN1), BUTTON_PRESSED(EN2) }; - #if ENCODER_DEBOUNCE_MS + #if defined(USE_COUNTER_DEBOUNCING) + static uint16_t counter; + counter++; + + static int dt_us = 500; // the time delta in us between each run of this function + if (counter == 1000){ + static millis_t last_ms; + dt_us = (now-last_ms); + last_ms = now; + counter = 0; + } + + static enc_t enc; + #define THRESHOLD (ENCODER_DEBOUNCE_MS * 1000 / 2) + static int16_t btn_a_counter = 0; + if (btn_a_counter < THRESHOLD && live_enc.a) btn_a_counter += dt_us; + else if (btn_a_counter > -THRESHOLD && !live_enc.a) btn_a_counter -= dt_us; + if (btn_a_counter >= THRESHOLD) enc.a = 1; + else if (btn_a_counter <= -THRESHOLD) enc.a = 0; + + static int16_t btn_b_counter = 0; + if (btn_b_counter < THRESHOLD && live_enc.b) btn_b_counter += dt_us; + else if (btn_b_counter > -THRESHOLD && !live_enc.b) btn_b_counter -= dt_us; + if (btn_b_counter >= THRESHOLD) enc.b = 1; + else if (btn_b_counter <= -THRESHOLD) enc.b = 0; + + #elif defined(USE_TIME_BLOCK_DEBOUNCING) static enc_t enc, old_live; static millis_t bounce_ms;