-
Notifications
You must be signed in to change notification settings - Fork 0
/
btn.h
51 lines (43 loc) · 1.55 KB
/
btn.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#define debounce 50
#define holdTime 1000
class Btn {
int buttonVal = 0; // value read from button
int buttonLast = HIGH; // buffered value of the button's previous state
long btnDnTime; // time the button was pressed down
long btnUpTime; // time the button was released
long lastHeld = 0;
boolean ignoreUp = false; // whether to ignore the button release because the click+hold was triggered
int buttonPin;
public:
Btn(int pin) : buttonPin(pin) {
pinMode(pin, INPUT_PULLUP);
}
bool pressed() {
return buttonLast == LOW;
}
void poll(void (*pressed)(), void (*held)()) {
// Read the state of the button
buttonVal = digitalRead(buttonPin);
// Test for button pressed and store the down time
if (buttonVal == LOW && buttonLast == HIGH && (millis() - btnUpTime) > long(debounce)) {
btnDnTime = millis();
}
// Test for button release and store the up time
if (buttonVal == HIGH && buttonLast == LOW && (millis() - btnDnTime) > long(debounce)) {
if (ignoreUp == false) {
if (pressed) pressed();
}
else ignoreUp = false;
btnUpTime = millis();
}
// Test for button held down for longer than the hold time
if (buttonVal == LOW && (millis() - btnDnTime) > long(holdTime)) {
if ((millis() - lastHeld) > 30) {
if (held) held();
lastHeld = millis();
}
ignoreUp = true;
}
buttonLast = buttonVal;
}
};