#105Beginner
ESP32 LED Control with Pushbutton (Toggle)
Each time the button is pressed the state of the LED changes: if it is on it turns off, if it is off it turns on. Classic toggle pattern. With debounce we clean up the mechanical noise of the pushbutton to ensure a single toggle with a single press.
4.6(37)
50 completed

Each time the button is pressed the state of the LED changes: if it is on it turns off, if it is off it turns on. Classic toggle pattern. With debounce we clean up the mechanical noise of the pushbutton to ensure a single toggle with a single press.
Video
Circuit Diagram

Source Code
1const int LED_PIN = 5;
2const int BUTTON_PIN = 4;
3
4bool ledState = false;
5bool lastButton = HIGH;
6unsigned long lastPress = 0;
7const unsigned long DEBOUNCE = 50;
8
9void setup() {
10 pinMode(LED_PIN, OUTPUT);
11 pinMode(BUTTON_PIN, INPUT_PULLUP);
12}
13
14void loop() {
15 bool buttonState = digitalRead(BUTTON_PIN);
16
17 if (buttonState == LOW && lastButton == HIGH && (millis() - lastPress > DEBOUNCE)) {
18 ledState = !ledState;
19 digitalWrite(LED_PIN, ledState);
20 lastPress = millis();
21 }
22 lastButton = buttonState;
23}