ESP32 Toggle LED: A Beginner's Guide to Controlling LEDs with ESP32

Introduction

The ESP32 is a powerful microcontroller that has gained popularity due to its versatility and ease of use. One of the most basic yet essential projects with the ESP32 is controlling an LED. This article will walk you through toggling an LED using the ESP32 board, along with the necessary code and essential information.

Components Needed

Before we begin, make sure you have the following items ready.

  1. ESP32 development board (e.g., NodeMCU, Wemos D1 Mini ESP32)
  2. Breadboard and jumper wires
  3. LED (any color)
  4. Resistor (around 220 ohms to limit current flow through the LED)
  5. Micro-USB cable for programming and powering the ESP32
  6. Arduino IDE (Integrated Development Environment) installed on your computer.

Setting up Arduino IDE for ESP32

Follow the steps to install and set up Arduino IDE for ESP32 on your computer. For details tutorial, visit:

Step 1: Install Arduino IDE

If you haven't already, download and install the Arduino IDE from the official website, download Arduino IDE first: https://www.arduino.cc/en/software

Step 2: Install ESP32 Board Manager Package

  1. Open the Arduino IDE.
  2. Go to "File" > "Preferences" (on Windows) or "Arduino" > "Preferences" (on macOS).
  3. In the "Additional Boards Manager URLs" field, enter the following URL:
    https://dl.espressif.com/dl/package_esp32_index.json alert-info
  4. If there is already a URL in the field, separate multiple URLs using commas.
  5. Click "OK" to save the preferences.

Step 3: Install ESP32 Board Package

  1. Go to "Tools" > "Board" > "Boards Manager..."
  2. In the search bar, type "ESP32".
  3. Look for "esp32" by Espressif Systems and click the "Install" button. This will download and install the necessary files for programming ESP32 boards with the Arduino IDE.

ESP32 GPIO Pins and LED Connection Circuit

The ESP32 development board has several General Purpose Input/Output (GPIO) pins that can control external components like LEDs. Before connecting an LED to the board, it's important to understand the pin configuration. The ESP32 has numerous GPIO pins, but for this project, we will use GPIO 2, which is conveniently accessible on most development boards.

ESP32 LED Circuit Diagram
ESP32 LED Circuit Diagram

  1. Connect the LED's longer leg (Anode) to the GPIO pin (e.g., GPIO 2) of the ESP32 using a jumper wire.
  2. Connect the LED's shorter leg (Cathode) to the ground (GND) pin on the ESP32 using another jumper wire.
  3. Place the 220-ohm resistor between the Anode of the LED and the GPIO pin to limit the current flow and prevent damage to the LED and ESP32.

Ensure that all connections are secure and that no loose wires or short circuits could potentially harm the components or the board. alert-warning

ESP32 built-in LED

The specific GPIO PINs for the built-in LEDs may vary depending on the board. Two popular ESP32 boards that most beginners encounter are the ESP32-DevKit and ESP32-CAM.

  • ESP32-DevKit: The ESP32-DevKit, also known as the ESP32-DevKitC, is a widely used ESP32 development board. It typically comes with a built-in LED connected to GPIO pin 2. This LED can be used for basic testing and visual feedback during development.
  • ESP32-CAM: The ESP32-CAM is a unique ESP32 board with a camera module, making it ideal for video streaming and image capture projects. On the ESP32-CAM board, you will find a built-in LED connected to GPIO pin 4. This LED provides status indications while working with the camera module.

Many other ESP32-based development boards might have built-in LEDs, but their GPIO pin assignments can differ from those mentioned above. When using a different ESP32 board, referring to the board's documentation or schematic is essential to identify the specific GPIO pin assigned to the built-in LED.

Programming the ESP32

Let's write the code to toggle the LED on and off. We will use the Arduino IDE to program the ESP32, so ensure you have it installed on your computer.

// ESP32 Toggle LED Example
const int ledPin = 2; // GPIO 2
void setup() {
  pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}
void loop() {
  digitalWrite(ledPin, HIGH); // Turn ON the LED
  delay(1000); // Wait for 1 second (1000 milliseconds)
  digitalWrite(ledPin, LOW); // Turn OFF the LED
  delay(1000); // Wait for 1 second
}code-box

Explanation of the Code

  1. We define a constant variable ledPin, and set it to 2, corresponding to GPIO 2 on the ESP32 board.
  2. In the setup() function, we set ledPin as output using pinMode(ledPin, OUTPUT).
  3. The loop() function is where the LED toggling takes place. We use digitalWrite(ledPin, HIGH) to turn ON the LED and then delay(1000) to wait for 1 second.
  4. After 1 second, we use digitalWrite(ledPin, LOW) to turn OFF the LED, followed by another delay(1000) to wait for another second.
  5. The process repeats indefinitely, resulting in the LED blinking ON and OFF repeatedly.

Uploading the Code

  1. Connect the ESP32 to your computer using a USB cable.
  2. Open the Arduino IDE and select the appropriate board and port from the "Tools" menu.
  3. Copy the code into the Arduino IDE.
  4. Click the "Upload" button to compile and upload the code to the ESP32.
  5. After successfully uploading, you should see the LED blinking ON and OFF at 1-second intervals.

Conclusion

Congratulations! You have successfully learned how to toggle an LED using an ESP32. This simple project lays the foundation for more complex IoT projects that control various electronic components. As you progress, you can explore using different GPIO pins, controlling multiple LEDs, and integrating various sensors to create more sophisticated applications. Happy tinkering!

16/Post a Comment/Comments

  1. I want to ask about the possibility of using the esp32 as hardware in the loop, or how to program the esp32 to simulate a dynamic system like a dc motor and plot the speed and the current with time.

    ReplyDelete
    Replies
    1. Certainly! To use the ESP32 for hardware-in-the-loop (HIL) simulations like simulating a DC motor and plotting speed and current, follow these steps:

      Model the System: Create a mathematical model of the DC motor.

      Simulate: Use software to simulate the motor's behavior and control responses.

      ESP32 Control: Write code to control the simulated motor using ESP32.

      Sensor Emulation: Simulate sensor data based on the model's output.

      Data Logging: Collect and store data from the ESP32.

      Plotting: Visualize motor behavior using tools like Python's matplotlib.

      Tuning: Adjust control parameters iteratively.

      Validation: Compare results with real-world tests for validation.

      Delete
  2. This tool is very practical

    ReplyDelete
  3. Thanks for the information about toggle an LED using an ESP32. Its very useful article. By this article we clearly know about different GPIO pins, controlling multiple LEDs & various sensors . Thanks

    ReplyDelete
    Replies
    1. Thank you for your kind words! I'm glad you found the article useful. Feel free to ask if you have any more questions or need further assistance with your ESP32 projects. Happy tinkering.

      Delete
  4. This comment has been removed by a blog administrator.

    ReplyDelete
  5. Wow 😲, so insightful i didnt know about this at all i gained so much knwoledge with one post , great article😍

    ReplyDelete
    Replies
    1. Thank you so much for your kind words! I'm thrilled to hear that you found the article insightful and gained valuable knowledge from it. If you have any more questions or need further information, feel free to ask. Happy learning! 😊

      Delete
  6. i got information about activating LED using ESP32. In this article we know clearly about various GPIO pins, controlling many LEDs very useful article thanks

    ReplyDelete
  7. I want to ask about the possibility of using the esp32 as hardware in the loop, or how to program the esp32 to simulate a dynamic system like a dc motor and plot the speed and the current with time.

    ReplyDelete
    Replies
    1. Hardware-in-the-Loop (HIL) simulation involves using real hardware to interact with a simulated environment. In the case of an ESP32 simulating a dynamic system like a DC motor, you can create a simulation environment on the ESP32 that models the behavior of the motor and then interface it with a computer for control and monitoring.

      Here's a simplified example using an ESP32 to simulate a DC motor, measure speed and current, and send the data to a computer for plotting:

      ESP32 Code:

      #include

      const int motorPin = 5; // GPIO pin connected to the simulated DC motor

      void setup() {
      Serial.begin(115200);
      pinMode(motorPin, OUTPUT);
      }

      void loop() {
      // Simulate motor behavior
      analogWrite(motorPin, 128); // Simulated PWM value

      // Measure speed and current (these are just placeholders, replace with actual simulation logic)
      float simulatedSpeed = analogRead(A0); // Simulated speed value
      float simulatedCurrent = analogRead(A1); // Simulated current value

      // Send data to computer
      Serial.print("Speed: ");
      Serial.print(simulatedSpeed);
      Serial.print(", Current: ");
      Serial.println(simulatedCurrent);

      delay(100); // Adjust delay based on your simulation requirements
      }
      Python Code (on the computer):
      Assuming you are using a serial connection to communicate between the ESP32 and the computer, you can use Python to read the serial data and plot it. Here's a simple example using the matplotlib library for plotting:


      import serial
      import matplotlib.pyplot as plt

      ser = serial.Serial('COMx', 115200) # Replace 'COMx' with the appropriate COM port

      speed_data = []
      current_data = []

      try:
      while True:
      data = ser.readline().decode().strip().split(',')
      if len(data) == 2:
      speed_data.append(float(data[0].split(':')[1]))
      current_data.append(float(data[1].split(':')[1]))

      plt.plot(speed_data, label='Speed')
      plt.plot(current_data, label='Current')
      plt.xlabel('Time')
      plt.ylabel('Values')
      plt.legend()
      plt.pause(0.1)

      except KeyboardInterrupt:
      ser.close()
      print("Serial connection closed.")
      Important Notes:
      The ESP32 code provides a basic simulation of a DC motor. You'll need to replace the simulation logic with a more accurate model depending on your specific requirements.

      Ensure that you have the necessary Python libraries installed, including matplotlib.

      The COM port in the Python code ('COMx') needs to be replaced with the actual COM port your ESP32 is connected to.

      This is a simplified example. Depending on the complexity of your simulation, you might need more advanced modeling techniques.

      Remember that HIL simulation requires accurate modeling to be effective, so the simulation logic in the ESP32 code should represent the behavior of a DC motor as closely as possible. Adjust the code based on your specific motor model and simulation requirements.

      Delete
  8. Your articles are beautiful, I benefited a lot from them

    ReplyDelete
  9. This information would go a long way and help me

    ReplyDelete
  10. This is very useful

    ReplyDelete

Post a Comment