Skip to content

Instantly share code, notes, and snippets.

@mzero
Created November 28, 2020 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzero/c5165429aa14413271dfe667ead0a6e6 to your computer and use it in GitHub Desktop.
Save mzero/c5165429aa14413271dfe667ead0a6e6 to your computer and use it in GitHub Desktop.
#include <Arduino.h>
class DebouncedSwitch {
public:
DebouncedSwitch(int p, int mode=INPUT_PULLDOWN) : pin(p), nextValidAt(0) {
pinMode(pin, mode);
state = nextState = digitalRead(pin);
}
bool update() {
// returns true if state has changed
unsigned long now = millis();
int currentState = digitalRead(pin);
if (currentState != nextState) {
nextState = currentState;
nextValidAt = now + settleTime;
}
else {
if (nextValidAt && now >= nextValidAt) {
state = nextState;
nextValidAt = 0;
return true;
}
}
return false;
}
int read() const { return state; }
// return the current state (after debouncing)
private:
const int pin;
int state;
int nextState;
unsigned long nextValidAt;
const unsigned long settleTime = 50; // in milliseconds
};
DebouncedSwitch btnA(4); // or whatever pin number you need
DebouncedSwitch btnB(5);
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("I'm ready!");
}
void loop() {
if (btnA.update()) {
Serial.print("switch A just changed to ");
Serial.println(btnA.read() ? "HIGH" : "LOW");
}
if (btnB.update()) {
Serial.print("switch B just changed to ");
Serial.println(btnB.read() ? "HIGH" : "LOW");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment