#define LED_PIN 21
#define BUTTON_PIN 33
int ledState = HIGH; // make sure to initialise this in setup
int buttonState = LOW; // button is wired : released -> LOW
// 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(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
// turn on the LED to match the state var initialisation
digitalWrite(LED_PIN, HIGH);
}
// we want to identify a new button press,
// then when we press the button we want to toggle the button
// so we need function toggle make it HIGH if it is LOW and
// make it LOW if it is currently HIGH
void toggleLEDState() {
if (ledState == HIGH) {
ledState = LOW;
} else {
ledState = HIGH;
}
}
void loop() {
// we also need to detect a button press when we press or
// release the button, so when the buttonState changes
// we do not want to poll the switch and constantly toggle
// the LED while the button is high
// 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;
// PLAN ACTION - change the state variables
if (buttonState == HIGH) {
Serial.print("take action code block: ledState ");
Serial.print(ledState);
toggleLEDState();
Serial.print(" -> ");
Serial.println(ledState);
}
}
}
// this is where we DO the planned action
// write the state to the LED
digitalWrite(LED_PIN, ledState);
delay(10);
}