-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathButton.h
50 lines (41 loc) · 853 Bytes
/
Button.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
class Button {
public:
Button(int pin);
bool pressed();
const static bool PRESSED = LOW;
const static bool RELEASED = HIGH;
private:
const unsigned long READ_DELAY = 50;
int pin;
unsigned long readDelayTo;
bool state = RELEASED;
bool justChangedState = false;
bool hasJustChanged();
bool read();
};
Button::Button(int pin) {
this->pin = pin;
pinMode(pin, INPUT_PULLUP);
}
bool Button::pressed() {
return read() == PRESSED && hasJustChanged();
}
bool Button::read()
{
if (readDelayTo < millis())
{
if (state != digitalRead(pin)) {
state = ! state;
readDelayTo = millis() + READ_DELAY;
justChangedState = true;
}
}
return state;
}
bool Button::hasJustChanged() {
if (justChangedState) {
justChangedState = false;
return true;
}
return false;
}