-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathButton.cpp
66 lines (56 loc) · 1.33 KB
/
Button.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* Project: ReflowOven
* File: Button.cpp
* Author: Sandro Lutz
*/
#include "Button.h"
#define DEBOUNCED_STATE 0
#define UNSTABLE_STATE 1
#define STATE_CHANGED 3
void Button::attach(uint8_t pin)
{
state = 0;
this->pin = pin;
pinMode(pin, INPUT_PULLUP);
}
bool Button::pressed()
{
return changed() && (bool)(state & (1<<DEBOUNCED_STATE));
}
bool Button::released()
{
return changed() && !(bool)(state & (1<<DEBOUNCED_STATE));
}
bool Button::changed()
{
return (bool)(state & (1<<STATE_CHANGED));
}
bool Button::down()
{
return (bool)(state & (1<<DEBOUNCED_STATE));
}
bool Button::up()
{
return !down();
}
bool Button::update()
{
// clear flag indicating state change
state &= ~(1<<STATE_CHANGED);
bool currentState = digitalRead(pin) == LOW;
if(currentState != (bool)(state & (1<<UNSTABLE_STATE))) {
time = millis();
state ^= (1<<UNSTABLE_STATE);
} else {
if(getTimeDifference(time, millis()) >= BUTTON_INTERVAL) {
// BUTTON_INTERVAL time has passed without a state change.
if((bool)(state & (1<<DEBOUNCED_STATE)) != currentState) {
time = millis();
state ^= (1<<DEBOUNCED_STATE);
state |= (1<<STATE_CHANGED);
return true;
}
}
}
return false;
}