-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lopa_Button.cpp
64 lines (51 loc) · 1.18 KB
/
Lopa_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
#include <Arduino.h>
#include <Lopa_Button.h>
namespace Lopa {
/** mode -- INPUT or INPUT_PULLUP **/
Button::Button(uint8_t pin, uint8_t mode)
{
_pin = pin;
pinMode(_pin, mode);
_prev_state = (digitalRead(_pin) == HIGH);
}
void Button::setDebounceTimeout(uint16_t debounce_timeout) {
_debounce_timeout = debounce_timeout;
}
bool Button::onPressed() {
_processButton();
if (_has_been_pressed) {
_has_been_pressed = false;
return true;
} else
return false;
}
bool Button::onReleased() {
_processButton();
if (_has_been_released) {
_has_been_released = false;
return true;
} else
return false;
}
bool Button::isPressed() {
_processButton();
return !_prev_state;
}
bool Button::isReleased() {
_processButton();
return _prev_state;
}
//private
void Button::_processButton() {
_cur_state = (digitalRead(_pin) == HIGH);
if (_prev_state == _cur_state)
time = millis();
else {
if (millis() - time > _debounce_timeout) {
_has_been_pressed = _prev_state;
_has_been_released = !_prev_state;
_prev_state = _cur_state;
}
}
}
}