Skip to content

Commit

Permalink
Counter based debouncing
Browse files Browse the repository at this point in the history
  • Loading branch information
dbuezas committed Mar 14, 2024
1 parent 00b8733 commit 41c8892
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions Marlin/src/lcd/marlinui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down

0 comments on commit 41c8892

Please sign in to comment.