From 4d1269051b9fc9e2b0fdbd7bdd6ba8a631fd7b80 Mon Sep 17 00:00:00 2001 From: Mark Thompson <129641948+NotherNgineer@users.noreply.github.com> Date: Sun, 21 May 2023 19:06:37 -0500 Subject: [PATCH] Fixed debounce code to handle noisy switch transitions #989 (#1030) * Fix debounce to handle noisy switch transitions * Fix debounce to handle noisy switch transitions * Fix debounce to handle noisy switch transitions * Removed inline comment to see if Clang checker will be happy * Test fix for supposed Clang formatting issue --- firmware/application/hw/debounce.cpp | 23 +++++++++++++++-------- firmware/application/hw/debounce.hpp | 4 ++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/firmware/application/hw/debounce.cpp b/firmware/application/hw/debounce.cpp index 2e338a102..7caf4ed22 100644 --- a/firmware/application/hw/debounce.cpp +++ b/firmware/application/hw/debounce.cpp @@ -23,17 +23,24 @@ #include "utility.hpp" +// Returns TRUE if button state changed (after debouncing) bool Debounce::feed(const uint8_t bit) { history_ = (history_ << 1) | (bit & 1); - if (history_ == 0b00001111) { - state_ = 1; - return true; + if (state_ == 0) { + // Previous button state was 0 (released); + // Has button been held for DEBOUNCE_COUNT ticks? + if ((history_ & DEBOUNCE_MASK) == DEBOUNCE_MASK) { + state_ = 1; + return true; + } + } else { + // Previous button state was 1 (pressed); + // Has button been released for DEBOUNCE_COUNT ticks? + if ((history_ & DEBOUNCE_MASK) == 0) { + state_ = 0; + return true; + } } - if (history_ == 0b11110000) { - state_ = 0; - return true; - } - return false; } diff --git a/firmware/application/hw/debounce.hpp b/firmware/application/hw/debounce.hpp index 0d2ba1cd7..52dfe1061 100644 --- a/firmware/application/hw/debounce.hpp +++ b/firmware/application/hw/debounce.hpp @@ -24,6 +24,10 @@ #include +// consecutive # of times button input must be same (<=8) +#define DEBOUNCE_COUNT 4 +#define DEBOUNCE_MASK ((1 << DEBOUNCE_COUNT) - 1) + class Debounce { public: bool feed(const uint8_t bit);