-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebounceButton.cpp
More file actions
35 lines (30 loc) · 1.35 KB
/
DebounceButton.cpp
File metadata and controls
35 lines (30 loc) · 1.35 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
#include "DebounceButton.h"
#include "limits.h"
DebounceButton::DebounceButton(uint8_t pin, uint8_t mode, bool push, uint8_t delay) : pin(pin), debounceDelay(delay), lastStateChangeTime(millis()), lastState(!push), pushState(push) {
pinMode(pin, mode);
}
bool DebounceButton::getPush(){
const bool pinState = digitalRead(pin);
return isStateChanged(pinState) && (pinState == pushState);
}
bool DebounceButton::isStateChanged(const bool pinState){
bool timeToReadNewValue = false;
//Implementing debouce functionality by ignoring all changes that happens {this->debounceDelay}ms after the last pin state change.
const unsigned long currentTime = millis();
if(currentTime > lastStateChangeTime){
//normal case where there have been some time since last call
timeToReadNewValue = ( currentTime-lastStateChangeTime > debounceDelay );
}else if(currentTime < lastStateChangeTime){
//special case when the millis timer has done a overflow since last call
timeToReadNewValue = ( (ULONG_MAX-lastStateChangeTime)+currentTime > debounceDelay );
}else{
//time is unchanged since last call
return false;
}
if( timeToReadNewValue && (pinState != lastState) ){
lastState = pinState;
lastStateChangeTime = currentTime;
return true;
}
return false;
}