-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButtonLib.cpp
More file actions
46 lines (36 loc) · 1.17 KB
/
ButtonLib.cpp
File metadata and controls
46 lines (36 loc) · 1.17 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
#include "ButtonLib.h"
Button::Button(int pin, unsigned long debounceDelay, unsigned long longPressDelay)
: _pin(pin), _debounceDelay(debounceDelay), _longPressDelay(longPressDelay),
_lastState(HIGH), _currentState(HIGH), _lastDebounceTime(0),
_pressStartTime(0), _longPressDetected(false) {}
void Button::begin() {
pinMode(_pin, INPUT_PULLUP);
_lastState = digitalRead(_pin);
}
void Button::update() {
bool reading = digitalRead(_pin);
if (reading != _lastState) {
_lastDebounceTime = millis();
}
if ((millis() - _lastDebounceTime) > _debounceDelay) {
if (reading != _currentState) {
_currentState = reading;
if (_currentState == LOW) {
_pressStartTime = millis();
_longPressDetected = false;
} else {
_pressStartTime = 0;
}
}
}
if (_currentState == LOW && !_longPressDetected && (millis() - _pressStartTime) > _longPressDelay) {
_longPressDetected = true;
}
_lastState = reading;
}
bool Button::isPressed() {
return _currentState == LOW;
}
bool Button::isLongPressed() {
return _longPressDetected;
}