From c26419a5a2eb83c07bcb69e8073cecd7453c53bf Mon Sep 17 00:00:00 2001 From: Arjan Mels Date: Mon, 12 Nov 2018 19:14:27 +0100 Subject: [PATCH] Remove busy waiting loop --- src/DebounceEvent.cpp | 18 ++++++++++-------- src/DebounceEvent.h | 2 ++ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/DebounceEvent.cpp b/src/DebounceEvent.cpp index b970948..cb1ab81 100644 --- a/src/DebounceEvent.cpp +++ b/src/DebounceEvent.cpp @@ -42,6 +42,7 @@ void DebounceEvent::_init(uint8_t pin, uint8_t mode, unsigned long delay, unsign _status = (_mode == BUTTON_SWITCH) ? digitalRead(_pin) : _defaultStatus; _delay = delay; _repeat = repeat; + _debounce_status = false; // set up button #if ESP8266 @@ -68,13 +69,16 @@ unsigned char DebounceEvent::loop() { unsigned char event = EVENT_NONE; - if (digitalRead(_pin) != _status) { - - // Debounce - unsigned long start = millis(); - while (millis() - start < _delay) delay(1); + if (!_debounce_status && digitalRead(_pin) != _status) { + _debounce_status = true; + _debounce_start = millis(); + } - if (digitalRead(_pin) != _status) { + if (_debounce_status && millis() > _debounce_start + _delay) { + + _debounce_status = false; + + if ( digitalRead(_pin) != _status ) { _status = !_status; @@ -105,9 +109,7 @@ unsigned char DebounceEvent::loop() { _ready = false; } - } - } } diff --git a/src/DebounceEvent.h b/src/DebounceEvent.h index 5844ee8..b76969a 100644 --- a/src/DebounceEvent.h +++ b/src/DebounceEvent.h @@ -60,6 +60,8 @@ class DebounceEvent { bool _status; bool _ready = false; bool _reset_count = true; + unsigned long _debounce_start; + bool _debounce_status; unsigned long _event_start; unsigned long _event_length; unsigned char _event_count = 0;