/*
* Debounce sketch for ESP32
* A switch connected to pin 2 lights the built-in LED
* Debounce logic prevents misreading of the switch state
*/
const int inputPin = 2; // the number of the input pin
const int debounceDelay = 10; // debounce time in milliseconds
bool last_button_state = LOW; // last state of the button
int ledState = LOW; // on or off (HIGH or LOW)
// debounce function to stabilize switch readings
bool debounce(int pin)
{
bool state;
bool previousState;
previousState = digitalRead(pin); // store switch state
for(int counter = 0; counter < debounceDelay; counter++)
{
delay(1); // wait for 1 ms
state = digitalRead(pin); // read the pin
if(state != previousState)
{
counter = 0; // reset the counter if state changes
previousState = state; // save current state
}
}
// switch state stable longer than debounce period
return state;
}
void setup()
{
pinMode(inputPin, INPUT_PULLUP); // enable internal pull-up resistor
pinMode(LED_BUILTIN, OUTPUT); // declare LED pin as output
}
void loop()
{
bool button_state = debounce(inputPin); // check debounced button state
// if button state changed and button was pressed
if(last_button_state != button_state && button_state == HIGH)
{
// toggle LED state
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
last_button_state = button_state; // update last button state
}