-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cpp
More file actions
63 lines (54 loc) · 1.3 KB
/
Button.cpp
File metadata and controls
63 lines (54 loc) · 1.3 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
/***************************************************
This is a debounced button library.
The state() method should be called multiple times
in loop() to check for both current state and state
change before considering the button to be either
pushed or released:
#include <Button.h>
Button button(2);
void setup() {
button.init();
}
void loop() {
bool changed;
if (button.state(changed) == HIGH && changed) {
// button was pressed
}
if (button.state(changed) == LOW && changed) {
// button was released
}
}
Written by John Calcote.
Version 1.0 - July 19, 2014
Adapted from http://arduino.cc/en/Tutorial/Debounce
Creative Commons License.
****************************************************/
#include <Button.h>
Button::Button(int pin, unsigned long delay)
: pin_(pin), delay_(delay), state_(LOW), lastState_(LOW), timer_(0)
{
}
void Button::init()
{
pinMode(pin_, INPUT);
}
int Button::state(bool& changed)
{
changed = false;
int reading = digitalRead(pin_);
unsigned long clock = millis();
if (reading != lastState_)
{
timer_ = clock; // state changed - reset timer
}
if (clock - timer_ > delay_)
{
if (reading != state_)
{
changed = true;
state_ = reading;
}
}
lastState_ = reading;
return state_;
}