From 019c6edc1dac429470583a28246631f701fdce2e Mon Sep 17 00:00:00 2001 From: eugene-makeev Date: Fri, 15 Jan 2021 01:30:10 +0300 Subject: [PATCH] Update Button.cpp Fix debounce algorithm. Original implementation does not filter noisy reads and return wrong value in case if short glitches appeared on the line. this value will remain for delay time and will be changed after. This is not what expected. --- Button.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Button.cpp b/Button.cpp index 746ce21..b1cc66b 100644 --- a/Button.cpp +++ b/Button.cpp @@ -11,6 +11,7 @@ Button::Button(uint8_t pin, uint16_t debounce_ms) : _pin(pin) , _delay(debounce_ms) , _state(HIGH) +, _debounce_state(_state) , _ignore_until(0) , _has_changed(false) { @@ -27,21 +28,20 @@ void Button::begin() bool Button::read() { - // ignore pin changes until after this delay time - if (_ignore_until > millis()) + // monitor pin changes during debounce time + if (digitalRead(_pin) != _state) { - // ignore any changes during this period + _state = !_state; + _ignore_until = millis() + _delay; } - - // pin has changed - else if (digitalRead(_pin) != _state) + // if no changes in debounce time, the button state stable, update value + else if (_ignore_until > millis()) { - _ignore_until = millis() + _delay; - _state = !_state; - _has_changed = true; + _has_changed = (_debounce_state != _state); + _debounce_state = _state; } - return _state; + return _debounce_state; } // has the button been toggled from on -> off, or vice versa