2017-11-17 17:55:32 +01:00
|
|
|
#ifndef _DEBOUNCE_H_
|
|
|
|
#define _DEBOUNCE_H_
|
2017-10-28 21:14:30 +02:00
|
|
|
|
2017-11-17 17:55:32 +01:00
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
enum class RawButtonEvent : uint8_t {
|
|
|
|
NoEvent,
|
|
|
|
Pressed,
|
|
|
|
Released,
|
|
|
|
};
|
|
|
|
|
|
|
|
template<uint16_t DEBOUNCE_PRESSED, uint16_t DEBOUNCE_UNPRESSED = DEBOUNCE_PRESSED>
|
|
|
|
class Debounce {
|
2017-11-17 17:55:32 +01:00
|
|
|
public:
|
|
|
|
enum class State : uint8_t {
|
|
|
|
Unpressed,
|
|
|
|
UnpressedDebounced,
|
|
|
|
Pressed,
|
|
|
|
PressedDebounced,
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
RawButtonEvent event(bool pressed) {
|
2017-11-17 17:55:32 +01:00
|
|
|
switch(state) {
|
|
|
|
case State::Unpressed :
|
|
|
|
if(pressed) {
|
|
|
|
state = State::PressedDebounced;
|
|
|
|
counter = millis();
|
2017-11-17 18:01:23 +01:00
|
|
|
return RawButtonEvent::Pressed;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::PressedDebounced :
|
2017-11-17 18:01:23 +01:00
|
|
|
if((uint16_t) millis() - counter > DEBOUNCE_PRESSED) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Pressed;
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::Pressed :
|
|
|
|
if(!pressed) {
|
|
|
|
state = State::UnpressedDebounced;
|
|
|
|
counter = millis();
|
2017-11-17 18:01:23 +01:00
|
|
|
return RawButtonEvent::Released;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::UnpressedDebounced :
|
2017-11-17 18:01:23 +01:00
|
|
|
if((uint16_t) millis() - counter > DEBOUNCE_UNPRESSED) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Unpressed;
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
return RawButtonEvent::NoEvent;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
2017-11-17 18:01:23 +01:00
|
|
|
|
2017-11-17 17:55:32 +01:00
|
|
|
private:
|
|
|
|
State state = State::Unpressed;
|
2017-11-17 18:01:23 +01:00
|
|
|
uint16_t counter = 0;
|
2017-10-28 21:14:30 +02:00
|
|
|
};
|
|
|
|
|
2017-11-17 17:55:32 +01:00
|
|
|
#endif
|