Last active
July 21, 2023 05:27
-
-
Save erikpena/a01ace32f7bef4a5ec52 to your computer and use it in GitHub Desktop.
A simple hardware button debouncer using ESP8266 libraries within the Arduino IDE.
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
// pin is 2. | |
const int multiButton = 2; | |
void setup() { | |
// Configure the pin mode as an input. | |
pinMode(multiButton, INPUT); | |
// Attach an interrupt to the pin, assign the onChange function as a handler and trigger on changes (LOW or HIGH). | |
attachInterrupt(multiButton, onChange, CHANGE); | |
Serial.begin(9600); | |
} | |
void loop() { | |
// Main part of your loop code. | |
} | |
// Holds the current button state. | |
volatile int state; | |
// Holds the last time debounce was evaluated (in millis). | |
volatile long lastDebounceTime = 0; | |
// The delay threshold for debounce checking. | |
const int debounceDelay = 50; | |
// Gets called by the interrupt. | |
void onChange() { | |
// Get the pin reading. | |
int reading = digitalRead(multiButton); | |
// Ignore dupe readings. | |
if(reading == state) return; | |
boolean debounce = false; | |
// Check to see if the change is within a debounce delay threshold. | |
if((millis() - lastDebounceTime) <= debounceDelay) { | |
debounce = true; | |
} | |
// This update to the last debounce check is necessary regardless of debounce state. | |
lastDebounceTime = millis(); | |
// Ignore reads within a debounce delay threshold. | |
if(debounce) return; | |
// All is good, persist the reading as the state. | |
state = reading; | |
// Work with the value now. | |
Serial.println("button: " + String(reading)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it's software debounce of a hardware button ;-)
But another nitpick: I had "surprising" results with Serial() stuff in an interrupt routine (panics, crashes, random resets), so I'd advise against that.