-
Notifications
You must be signed in to change notification settings - Fork 29
/
Button.cpp
75 lines (63 loc) · 1.28 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
67
68
69
70
71
72
73
74
75
/*
Button - a small library for Arduino to handle button debouncing
MIT licensed.
*/
#include "Button.h"
#include <Arduino.h>
Button::Button(uint8_t pin, uint16_t debounce_ms)
: _pin(pin)
, _delay(debounce_ms)
, _state(HIGH)
, _ignore_until(0)
, _has_changed(false)
{
}
void Button::begin()
{
pinMode(_pin, INPUT_PULLUP);
}
//
// public methods
//
bool Button::read()
{
// ignore pin changes until after this delay time
if (_ignore_until > millis())
{
// ignore any changes during this period
}
// pin has changed
else if (digitalRead(_pin) != _state)
{
_ignore_until = millis() + _delay;
_state = !_state;
_has_changed = true;
}
return _state;
}
// has the button been toggled from on -> off, or vice versa
bool Button::toggled()
{
read();
return has_changed();
}
// mostly internal, tells you if a button has changed after calling the read() function
bool Button::has_changed()
{
if (_has_changed)
{
_has_changed = false;
return true;
}
return false;
}
// has the button gone from off -> on
bool Button::pressed()
{
return (read() == PRESSED && has_changed());
}
// has the button gone from on -> off
bool Button::released()
{
return (read() == RELEASED && has_changed());
}