Skip to content

Instantly share code, notes, and snippets.

@paccerdk
Created February 19, 2023 01:15
Show Gist options
  • Save paccerdk/3996879f7a42958194352bef8b7ac104 to your computer and use it in GitHub Desktop.
Save paccerdk/3996879f7a42958194352bef8b7ac104 to your computer and use it in GitHub Desktop.
example of debouncing for esp8266/esp32 using arduino framework
//This is how i typically handle button presses, while using a minimal amount of clock cycles / avoiding polling and still keeping it responsive:(note: interrupt callbacks should ideally be as simple as possible, so its better to have the logic outside of it.)
#include <Arduino.h>
#define GPIO_BUTTON 4
#define GPIO_LED 5
const uint16_t debounceDelay = 100;
unsigned long lastButtonPress = 0;
bool buttonPressed = false;
void IRAM_ATTR buttonInterrupt() {
buttonPressed = true;
}
void buttonHandler() {
if (buttonPressed) {
buttonPressed = false;
if (millis() - lastButtonPress > debounceDelay) {
lastButtonPress = millis();
//your button logic here
digitalWrite(GPIO_LED, !digitalRead(GPIO_LED));
}
}
}
void setup() {
pinMode(GPIO_BUTTON, INPUT_PULLUP);
pinMode(GPIO_LED, OUTPUT);
digitalWrite(GPIO_LED, LOW);
attachInterrupt(GPIO_BUTTON, buttonInterrupt, FALLING);
}
void loop() {
buttonHandler();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment