-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDebouncer.cpp
111 lines (94 loc) · 2.6 KB
/
Debouncer.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
____ _____ _ _
| __ )| ____| | / \
| _ \| _| | | / _ \
| |_) | |___| |___ / ___ \
|____/|_____|_____/_/ \_\
http://bela.io
C++ Real-Time Audio Programming with Bela - Lecture 14: ADSR
*/
// Debouncer.h: simple class to debounce a button
#include "Debouncer.h"
// Constructor
Debouncer::Debouncer()
{
setup(1, 1);
}
// Constructor specifying a sample rate
Debouncer::Debouncer(float sampleRate, float interval)
{
setup(sampleRate, interval);
}
// Set the sample rate, used for all calculations
void Debouncer::setup(float sampleRate, float interval)
{
debounceInterval_ = sampleRate * interval;
currentState_ = previousState_ = kStateLow;
counter_ = 0;
}
// Return the debounced state given the raw input
bool Debouncer::process(bool rawInput)
{
// Save the current state so that if it changes, the risingEdge() and
// fallingEdge() methods can detect it
previousState_ = currentState_;
// Run the state machine with the current input
if(currentState_ == kStateLow) {
// Button is low, but look for a high value
if(rawInput) {
// Found high input: move to just-high state
currentState_ = kStateJustHigh;
counter_ = 0;
}
}
else if(currentState_ == kStateJustHigh) {
// Button was just high, wait for debounce
// Run counter, wait for timeout
if(++counter_ >= debounceInterval_) {
// Timeout: now we can start waiting for the input to go low
currentState_ = kStateHigh;
}
}
else if(currentState_ == kStateHigh) {
// Button is high, could be low anytime
// Input: look for low input
if(!rawInput) {
currentState_ = kStateJustLow;
counter_ = 0;
}
}
else if(currentState_ == kStateJustLow) {
// Button was just low, wait for debounce
// Run counter, wait for timeout
if(++counter_ >= debounceInterval_) {
// Timeout: now we can start waiting for the input to go high
currentState_ = kStateLow;
}
}
return currentValue();
}
// Return whether the button is currently high or low
bool Debouncer::currentValue()
{
if(currentState_ == kStateHigh || currentState_ == kStateJustHigh)
return true;
return false;
}
// Return whether the button just now went high
bool Debouncer::risingEdge()
{
if(currentState_ == kStateJustHigh && previousState_ == kStateLow)
return true;
return false;
}
// Return whether the button just now went low
bool Debouncer::fallingEdge()
{
if(currentState_ == kStateJustLow && previousState_ == kStateHigh)
return true;
return false;
}
// Destructor
Debouncer::~Debouncer()
{
}