#define BUTTON_PIN 33
int buttonState = LOW; // button is wired : released -> LOW
// let's create a variable to count the number of presses
int counter = 0;
// declare the time variables to store current time and previous presses
unsigned long timeNow = millis();
unsigned long timePreviousButtonChange = millis();
// declare and initialise the 'ignore all presses within this interval'
// you can adjust this delay to see what it does
int debounceDelay = 50;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
// always set timeNow in the beginning of the loop, and only once
timeNow = millis();
// check if you are outside of the ignore all presses interval
if (timeNow - timePreviousButtonChange > debounceDelay) {
// we only enter this loop AFTER the debounce delay
// any presses inside this loop are considered
// we don't even look at the button state when it is too early
byte newButtonState = digitalRead(BUTTON_PIN);
// check to see if button state has changed
if (newButtonState != buttonState) {
// only enter this loop if the button state has changed
// the next two lines are virtual
// #1 update state variable
buttonState = newButtonState;
// #2 update the time to start a new debounce interval
timePreviousButtonChange = timeNow;
// this is where we take action, print the number of presses
if (buttonState == HIGH) {
counter += 1;
Serial.print("button pressed: ");
Serial.println(counter);
} else {
Serial.println("button released");
}
}
}
// no delay as we want to see bouncing in the serial monitor
//delay(10);
}