-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.h
More file actions
124 lines (104 loc) · 2.62 KB
/
Button.h
File metadata and controls
124 lines (104 loc) · 2.62 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Manage a button presses
#ifndef _BUTTON
#define _BUTTON
#define DefineButton(buttonName, pin) \
Button buttonName(pin); \
void buttonName##ISR() { buttonName.onInterrupt(); }
#define SetupButton(buttonName) \
buttonName.Setup(buttonName##ISR);
class Button
{
public:
Button(int pin)
{
m_pin = pin;
m_bIsPressed = false;
m_bWasPressed = false;
m_bWasLongPressed = false;
lastState = !bIsPressed;
lastStateChangeTime = millis();
}
void Setup(void(ISR)())
{
pinMode(m_pin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(m_pin), ISR, CHANGE);
}
void Reset()
{
m_bReset = true;
m_bIsPressed = false;
m_bWasPressed = false;
}
inline bool IsPressed() { return m_bIsPressed; }
bool WasPressed()
{
if (m_bWasPressed)
{
m_bWasPressed = false;
return true;
}
return false;
}
// Check if button was long pressed
bool WasLongPressed()
{
if (m_bWasLongPressed)
{
m_bWasLongPressed = false;
return true;
}
return false;
}
void onInterrupt()
{
unsigned long now = millis();
unsigned long timeSinceLastStateChange = now - lastStateChangeTime;
if (timeSinceLastStateChange > debounceDelay)
{
bool currentState = digitalRead(m_pin);
// Check if there was a state change
if (currentState != lastState)
{
lastStateChangeTime = now;
lastState = currentState;
m_bIsPressed = (currentState == bIsPressed);
// Once the button is released, we record that it was pressed
if (currentState != bIsPressed)
{
m_bWasPressed = true;
if (timeSinceLastStateChange > longPressDelay)
{
m_bWasLongPressed = true;
}
else
{
m_bWasLongPressed = false;
}
}
else
{
m_bWasLongPressed = false;
}
if (m_bReset)
{
m_bReset = false;
m_bIsPressed = false;
m_bWasPressed = false;
m_bWasLongPressed = false;
}
}
}
}
private:
static const unsigned long debounceDelay = 50;
static const unsigned long longPressDelay = 1000;
static const bool bIsPressed = LOW;
int m_pin;
unsigned long lastStateChangeTime;
bool lastState;
volatile bool m_bIsPressed;
volatile bool m_bWasPressed;
volatile bool m_bWasLongPressed;
volatile bool m_bReset;
};
#endif