multi click support including buzzer toggle

This commit is contained in:
taco
2025-09-03 08:25:59 +10:00
parent a93a0fecba
commit ce31fd7c57
4 changed files with 89 additions and 7 deletions

View File

@@ -9,6 +9,10 @@ MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, bool reverse
cancel = 0;
_long_millis = long_press_millis;
_threshold = 0;
_click_count = 0;
_last_click_time = 0;
_multi_click_window = 500;
_pending_click = false;
}
MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, int analog_threshold) {
@@ -20,6 +24,10 @@ MomentaryButton::MomentaryButton(int8_t pin, int long_press_millis, int analog_t
cancel = 0;
_long_millis = long_press_millis;
_threshold = analog_threshold;
_click_count = 0;
_last_click_time = 0;
_multi_click_window = 500;
_pending_click = false;
}
void MomentaryButton::begin() {
@@ -35,6 +43,8 @@ bool MomentaryButton::isPressed() const {
void MomentaryButton::cancelClick() {
cancel = 1;
_click_count = 0;
_pending_click = false;
}
bool MomentaryButton::isPressed(int level) const {
@@ -60,10 +70,14 @@ int MomentaryButton::check(bool repeat_click) {
// button UP
if (_long_millis > 0) {
if (down_at > 0 && (unsigned long)(millis() - down_at) < _long_millis) { // only a CLICK if still within the long_press millis
event = BUTTON_EVENT_CLICK;
_click_count++;
_last_click_time = millis();
_pending_click = true;
}
} else {
event = BUTTON_EVENT_CLICK; // any UP results in CLICK event when NOT using long_press feature
_click_count++;
_last_click_time = millis();
_pending_click = true;
}
if (event == BUTTON_EVENT_CLICK && cancel) {
event = BUTTON_EVENT_NONE;
@@ -87,5 +101,25 @@ int MomentaryButton::check(bool repeat_click) {
}
}
if (_pending_click && (millis() - _last_click_time) >= _multi_click_window) {
switch (_click_count) {
case 1:
event = BUTTON_EVENT_CLICK;
break;
case 2:
event = BUTTON_EVENT_DOUBLE_CLICK;
break;
case 3:
event = BUTTON_EVENT_TRIPLE_CLICK;
break;
default:
// For 4+ clicks, treat as triple click?
event = BUTTON_EVENT_TRIPLE_CLICK;
break;
}
_click_count = 0;
_pending_click = false;
}
return event;
}

View File

@@ -5,6 +5,8 @@
#define BUTTON_EVENT_NONE 0
#define BUTTON_EVENT_CLICK 1
#define BUTTON_EVENT_LONG_PRESS 2
#define BUTTON_EVENT_DOUBLE_CLICK 3
#define BUTTON_EVENT_TRIPLE_CLICK 4
class MomentaryButton {
int8_t _pin;
@@ -13,6 +15,10 @@ class MomentaryButton {
int _long_millis;
int _threshold; // analog mode
unsigned long down_at;
uint8_t _click_count;
unsigned long _last_click_time;
int _multi_click_window;
bool _pending_click;
bool isPressed(int level) const;