Created
August 27, 2014 21:07
-
-
Save egradman/45bb011ceb568e09c4a5 to your computer and use it in GitHub Desktop.
debouncer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Debouncer { | |
public: | |
int debounce_delay; | |
long high_edge_interval; | |
long last_transition_at; | |
bool last_val; | |
bool last_state; | |
bool state; | |
long last_valid_high_edge_at; | |
bool _did_go_high_valid; | |
Debouncer(int _debounce_delay=50, int _high_edge_interval=500) { | |
debounce_delay = _debounce_delay; | |
high_edge_interval = _high_edge_interval; | |
last_transition_at = 0; | |
last_val = -1; | |
last_state = -1; | |
state = -1; | |
} | |
void update(bool value) { | |
last_state = state; | |
if (value != last_val) { | |
last_val = value; | |
last_transition_at = millis(); | |
} | |
_did_go_high_valid = false; | |
if (millis() - last_transition_at > debounce_delay) { | |
state = value; | |
if (state && !last_state && millis() - last_valid_high_edge_at > high_edge_interval) | |
_did_go_high_valid = true; | |
last_valid_high_edge_at = millis(); | |
} | |
} | |
bool did_go_high_valid() { | |
return _did_go_high_valid; | |
} | |
bool did_change_state() { | |
return state != last_state; | |
} | |
bool get_state() { | |
return state; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment