2017-11-17 17:55:32 +01:00
|
|
|
#include "debounce.h"
|
|
|
|
|
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
enum class ButtonEvent : uint8_t {
|
|
|
|
NoEvent,
|
|
|
|
Press,
|
|
|
|
LongPress,
|
|
|
|
DoublePress,
|
|
|
|
};
|
2017-11-17 17:55:32 +01:00
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
// template wird komplett wegoptimiert (wie #define)
|
|
|
|
template<uint16_t LONGPRESS_TIMEOUT, uint16_t DOUBLEPRESS_TIMEOUT>
|
|
|
|
class Button {
|
2017-11-17 17:55:32 +01:00
|
|
|
public:
|
|
|
|
enum class State : uint8_t {
|
|
|
|
Idle,
|
|
|
|
Pressed,
|
|
|
|
LongPressed,
|
|
|
|
Released,
|
|
|
|
};
|
|
|
|
|
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
ButtonEvent event(RawButtonEvent result) {
|
2017-11-17 17:55:32 +01:00
|
|
|
switch(state) {
|
|
|
|
case State::Idle :
|
2017-11-17 18:01:23 +01:00
|
|
|
if(result == RawButtonEvent::Pressed) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Pressed;
|
|
|
|
counter = millis();
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::Pressed :
|
2017-11-17 18:01:23 +01:00
|
|
|
if(result == RawButtonEvent::Released) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Released;
|
|
|
|
counter = millis();
|
2017-11-17 18:01:23 +01:00
|
|
|
} else if((uint16_t) millis() - counter >= LONGPRESS_TIMEOUT) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::LongPressed;
|
2017-11-17 18:01:23 +01:00
|
|
|
return ButtonEvent::LongPress;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::Released :
|
2017-11-17 18:01:23 +01:00
|
|
|
if(result == RawButtonEvent::Pressed) {
|
|
|
|
state= State::Idle;
|
|
|
|
return ButtonEvent::DoublePress;
|
|
|
|
} else if((uint16_t) millis() - counter >= DOUBLEPRESS_TIMEOUT) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Idle;
|
2017-11-17 18:01:23 +01:00
|
|
|
return ButtonEvent::Press;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case State::LongPressed :
|
2017-11-17 18:01:23 +01:00
|
|
|
if(result == RawButtonEvent::Released) {
|
2017-11-17 17:55:32 +01:00
|
|
|
state = State::Idle;
|
|
|
|
} else {
|
2017-11-17 18:01:23 +01:00
|
|
|
return ButtonEvent::LongPress;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2017-11-17 18:01:23 +01:00
|
|
|
return ButtonEvent::NoEvent;
|
2017-11-17 17:55:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
State state = State::Idle;
|
|
|
|
uint16_t counter = 0;
|
|
|
|
};
|