ESP32 - Button - Toggle LED

In a previous tutorial, We have learned how to turn on the LED if the button is pressed, and turn off LED if the button is released. In this tutorial, We are going to learn how to toggle LED each time button is pressed.

We are going to learn how to:

  • Button toggles LED without debouncing.
  • Button toggles LED with debouncing.

Video Tutorial

you can watch this video tutorial

Hardware Required

1×ESP-WROOM-32 Dev Module
1×Micro USB Cable
1×Button
1×LED
1×220 ohm resistor
1×Breadboard
5×Jumper Wires

About LED and Button

If you do not have knowledge of LED and button (pinout, how they work, how to connect them to ESP32, how to program for them...), learn about them in the following tutorials:

Wiring Diagram

Schematic Diagram

ESP32 Button LED Wiring Diagram

Image is developed using Fritzing. Click to enlarge image

Breadboard Connections

ESP32 Button LED Wiring Diagram

Image is developed using Fritzing. Click to enlarge image

click to see ESP32 pin out

ESP32 Code Button Toggle LED without Debounce

Copy

const int BUTTON_PIN = 2;                      // ESP32 pin connected to button's pin
const int LED_PIN    = 13;                     // ESP32 pin connected to LED's pin


int ledState = LOW;                            // the current state of LED
int lastButtonState;                           // the previous state of button
int currentButtonState;                        // the current state of button

void setup() {
  Serial.begin(9600);                          // initialize serial
  pinMode(BUTTON_PIN, INPUT_PULLUP);           // set ESP32 pin to input pull-up mode
  pinMode(LED_PIN, OUTPUT);                    // set ESP32 pin to output mode

  currentButtonState = digitalRead(BUTTON_PIN);
}

void loop() {
  lastButtonState    = currentButtonState;      // save the last state
  currentButtonState = digitalRead(BUTTON_PIN); // read new state

  if(lastButtonState == HIGH && currentButtonState == LOW) {
    Serial.println("The button is pressed");

    ledState = !ledState;// toggle state of LED

    digitalWrite(LED_PIN, ledState);            // control LED arccoding to the toggled state
  }
}
                

Quick Steps

  • power up your board
  • Open Arduino IDE
  • Select the right board
  • Select the right port
  • Copy the above code and open with Arduino IDE
  • Click Upload button on Arduino IDE to upload code to ESP32
  • Arduino IDE Upload Code
  • Press and keep pressing the button several seconds
  • See the changes you made

Code Explanation

Read the line-by-line explanation in comment lines of source code!

In the code, ledState = !ledState is equivalent to the following code:

if(ledState == LOW)
   ledState = HIGH;
else
   ledState = LOW;

※ NOTE THAT:

In practice, the above code does not work correctly sometimes. To make it always work correctly, we need to debounce for the button.

ESP32 Code Button with Debounce

Copy

const int BUTTON_PIN = 2;                              // GIOP21 pin connected to button
const int LED_PIN    = 13;                             // ESP32 pin connected to LED's pin
const int DEBOUNCE_DELAY = 50;                         // the debounce time; increase if the output flickers

// Variables will change:
int ledState = LOW;     
int lastSteadyState = LOW;                             // the previous steady state from the input pin
int lastFlickerableState = LOW;                        // the previous flickerable state from the input pin
int currentState;                                      // the current reading from the input pin

                       // the following variables are unsigned longs because the time, measured in
                       // milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;                    // the last time the output pin was toggled

void setup() {
  
  Serial.begin(9600);                                  // initialize serial communication at 9600 bits per second:
  pinMode(BUTTON_PIN, INPUT_PULLUP);                   // initialize the pushbutton pin as an pull-up input
  pinMode(LED_PIN, OUTPUT);                            // set ESP32 pin to output mode
}

void loop() {
  currentState = digitalRead(BUTTON_PIN);              // read the state of the switch/button

                       // check to see if you just pressed the button
                       // (i.e. the input went from LOW to HIGH), and you've waited long enough
                       // since the last press to ignore any noise:
  if (currentState != lastFlickerableState) {          // If the switch/button changed, due to noise or pressing
    lastDebounceTime = millis();                       // reset the debouncing timer
    lastFlickerableState = currentState;               // save the the last flickerable state
  }

                       // whatever the reading is at, it's been there for longer than the debounce
                       // delay, so take it as the actual current state:
  if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
    if(lastSteadyState == HIGH && currentState == LOW)     // if the button state has changed
    {
      Serial.println("The button is pressed");
      ledState = !ledState;// toggle state of LED
      digitalWrite(LED_PIN, ledState);                     // control LED arccoding to the toggled state
    }   
    lastSteadyState = currentState;                        // save the the last steady state
  }
}                

Quick Steps

  • power up your board
  • Open Arduino IDE
  • Select the right board
  • Select the right port
  • Copy the above code and open with Arduino IDE
  • Click Upload button on Arduino IDE to upload code to ESP32
  • Press and keep pressing the button several seconds
  • See the changes you made

Book Tutorial

We are considering to make the book tutorials. If you think the book tutorials are essential, you can download it. download book

References

※ NOTE THAT:

Some components works on 3.3v and others works on 5v!