Skip to content

Commit d21dc4e

Browse files
committed
Merge pull request #1 from cyborgsimon/#15-button-debounce-time
Add debounce time check to button library
2 parents 8e86412 + f1a9c05 commit d21dc4e

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

framework/libraries/Button/Button.cpp

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ Button::Button(uint8_t buttonPin, uint8_t buttonMode)
4141
bitWrite(state, CURRENT, !mode);
4242

4343
lastPressStartTime = 0;
44+
debounceTime = 50;
4445

4546
cb_onPress = 0;
4647
cb_onRelease = 0;
@@ -114,8 +115,10 @@ bool Button::isPressed(void)
114115
{
115116
cb_onPress(*this); //fire the onPress event
116117
}
118+
//note that the state changed
119+
bitWrite(state, CHANGED, true);
117120
}
118-
else //the state changed to RELEASED
121+
else if (millis() - pressedStartTime >= debounceTime) //the state changed to RELEASED
119122
{
120123
if (cb_onRelease)
121124
{
@@ -134,9 +137,13 @@ bool Button::isPressed(void)
134137
lastPressStartTime = pressedStartTime;
135138
//reset states (for timing and for event triggering)
136139
pressedStartTime = -1;
140+
//note that the state changed
141+
bitWrite(state, CHANGED, true);
142+
}
143+
else {
144+
//note that the state did not change
145+
bitWrite(state, CHANGED, false);
137146
}
138-
//note that the state changed
139-
bitWrite(state, CHANGED, true);
140147
}
141148
else
142149
{
@@ -228,6 +235,16 @@ bool Button::heldFor(unsigned int time)
228235
return false;
229236
}
230237

238+
/*
239+
|| @description
240+
|| | Set the debounce time
241+
|| #
242+
*/
243+
void Button::setDebounceTime(unsigned int debounce)
244+
{
245+
debounceTime = debounce;
246+
}
247+
231248
/*
232249
|| @description
233250
|| | Set the hold event time threshold

framework/libraries/Button/Button.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class Button
4242
bool stateChanged();
4343
bool uniquePress();
4444

45+
void setDebounceTime(unsigned int debounce);
4546
void setHoldThreshold(unsigned int holdTime);
4647
bool held(unsigned int time = 0);
4748
bool heldFor(unsigned int time);
@@ -68,6 +69,7 @@ class Button
6869
uint8_t state;
6970
unsigned long pressedStartTime;
7071
unsigned long lastPressStartTime;
72+
unsigned int debounceTime;
7173
unsigned int holdEventThreshold;
7274
unsigned int multiClickEventThreshold;
7375
buttonEventHandler cb_onPress;

0 commit comments

Comments
 (0)