Skip to content

Instantly share code, notes, and snippets.

@erikpena
Last active July 21, 2023 05:27
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikpena/a01ace32f7bef4a5ec52 to your computer and use it in GitHub Desktop.
Save erikpena/a01ace32f7bef4a5ec52 to your computer and use it in GitHub Desktop.
A simple hardware button debouncer using ESP8266 libraries within the Arduino IDE.
// 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));
}
@hatkidchan
Copy link

well, this is software debounce, not hardware

@seife
Copy link

seife commented Jan 26, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment