-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBounce.cpp
97 lines (74 loc) · 1.89 KB
/
Bounce.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Please read Bounce.h for information about the liscence and authors
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Bounce.h"
Bounce::Bounce(uint8_t pin,unsigned long interval_millis)
{
interval(interval_millis);
previous_millis = millis();
state = digitalRead(pin);
this->pin = pin;
}
Bounce::Bounce() {
this->interval_millis = 10;
}
void Bounce::attach(int pin) {
previous_millis = millis();
state = digitalRead(pin);
this->pin = pin;
}
void Bounce::write(int new_state)
{
this->state = new_state;
digitalWrite(pin,state);
}
void Bounce::interval(unsigned long interval_millis)
{
this->interval_millis = interval_millis;
this->rebounce_millis = 0;
}
void Bounce::rebounce(unsigned long interval)
{
this->rebounce_millis = interval;
}
int16_t Bounce::update()
{
if ( debounce() ) {
rebounce(0);
return stateChanged = 1;
}
// We need to rebounce, so simulate a state change
if ( rebounce_millis && (millis() - previous_millis >= rebounce_millis) ) {
previous_millis = millis();
rebounce(0);
return stateChanged = 1;
}
return stateChanged = 0;
}
unsigned long Bounce::duration()
{
return millis() - previous_millis;
}
int16_t Bounce::read()
{
return (int)state;
}
// Protected: debounces the pin
uint16_t Bounce::debounce() {
uint8_t newState = digitalRead(pin);
if (state != newState ) {
if (millis() - previous_millis >= interval_millis) {
previous_millis = millis();
state = newState;
return 1;
}
}
return 0;
}
// The risingEdge method is true for one scan after the de-bounced input goes from off-to-on.
bool Bounce::risingEdge() { return stateChanged && state; }
// The fallingEdge method it true for one scan after the de-bounced input goes from on-to-off.
bool Bounce::fallingEdge() { return stateChanged && !state; }