diff --git a/src/Bounce2.cpp b/src/Bounce2.cpp index 84f928e..55712ba 100644 --- a/src/Bounce2.cpp +++ b/src/Bounce2.cpp @@ -49,8 +49,7 @@ bool Bounce::update() bool currentState = readCurrentState(); if ( currentState != getStateFlag(DEBOUNCED_STATE) ) { previous_millis = millis(); - toggleStateFlag(DEBOUNCED_STATE); - setStateFlag(CHANGED_STATE); + changeState(); } } @@ -68,8 +67,7 @@ bool Bounce::update() // set the STATE_CHANGED flag and the new DEBOUNCED_STATE. // This will be prompt as long as there has been greater than interval_misllis ms since last change of input. // Otherwise debounced state will not change again until bouncing is stable for the timeout period. - toggleStateFlag(DEBOUNCED_STATE); - setStateFlag(CHANGED_STATE ); + changeState(); } } @@ -97,17 +95,34 @@ bool Bounce::update() // If it is different from last state, set the STATE_CHANGED flag if (currentState != getStateFlag(DEBOUNCED_STATE) ) { previous_millis = millis(); - toggleStateFlag(DEBOUNCED_STATE); - setStateFlag(CHANGED_STATE) ; + + + changeState(); } } #endif -return getStateFlag(CHANGED_STATE); + return getStateFlag(CHANGED_STATE); } +/* +// WIP HELD +unsigned long Bounce::held() { + return durationOfPreviousState; +} +*/ +unsigned long Bounce::duration() { + return (millis() - stateChangeLastTime); +} + +inline void Bounce::changeState() { + toggleStateFlag(DEBOUNCED_STATE); + setStateFlag(CHANGED_STATE) ; + // WIP HELD : durationOfPreviousState = millis() - stateChangeLastTime; + stateChangeLastTime = millis(); +} bool Bounce::read() { diff --git a/src/Bounce2.h b/src/Bounce2.h index 8e6eebb..4b23a63 100644 --- a/src/Bounce2.h +++ b/src/Bounce2.h @@ -85,12 +85,20 @@ class Bounce attach(pin); interval(interval_millis); } + + // Returns the duration of the current state + unsigned long duration(); + + + // WIP HELD : unsigned long held(); // Returns the duration the previous state was held protected: unsigned long previous_millis; uint16_t interval_millis; uint8_t state; uint8_t pin; + unsigned long stateChangeLastTime; + // WIP HELD : unsigned long durationOfPreviousState; virtual bool readCurrentState() { return digitalRead(pin); } virtual void setPinMode(int pin, int mode) { #if defined(ARDUINO_STM_NUCLEO_F103RB) || defined(ARDUINO_GENERIC_STM32F103C) @@ -101,6 +109,7 @@ class Bounce } private: + inline void changeState(); inline void setStateFlag(const uint8_t flag) {state |= flag;} inline void unsetStateFlag(const uint8_t flag) {state &= ~flag;} inline void toggleStateFlag(const uint8_t flag) {state ^= flag;}