Created
November 28, 2020 19:34
-
-
Save mzero/c5165429aa14413271dfe667ead0a6e6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#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