Learn C++ with ESP32 : LED Control


Introduction

In embedded systems development, ESP32 is a popular development board known for its powerful processing and wireless communication features. In this article, we will use C++'s object-oriented features to create a class that controls an LED, learning how to develop on ESP32 in the process. We will implement the project using ESP-IDF (Espressif IoT Development Framework) and Visual Studio Code.

Setting up the Development Environment

1. Install Visual Studio Code: Download and install it from the official VS Code website.
2. Install the ESP-IDF Plugin: You can install the ESP-IDF extension for VS Code by searching for it in the Extensions tab.

Creating a New Project

1. Open Visual Studio Code, press Ctrl (Cmd) + Shift + P, and type ESP-IDF: New Project.

2. Select a template project (like the blink example), name your project (e.g., LED_Control), and choose the location to store it.

3. The system will automatically generate a new ESP-IDF project with basic CMake files and example code.

Project Structure

my_project/
├── CMakeLists.txt
├── main/
│ ├── CMakeLists.txt
│ └── main.cpp
└── ...
Learn C++ with ESP32 : LED Control

Using a C++ Class to Control the LED

Open the main/main.cpp file and modify it to include the following code:

Code Explanation

LEDController Class:
Provides three main methods:
1. turnOn(): Turns on the LED.
2. turnOff(): Turns off the LED.
3. blink(): Makes the LED blink once, with the interval specified as a parameter.
app_main() Function:
In the app_main() function, we perform the following actions:
1. Turn the LED on for 2 seconds.
2. Turn the LED off for 2 seconds.
3. Blink the LED 5 times, with a 500ms interval.
4. Turn the LED on for 3 more seconds.
5. Finally, turn the LED off.

Building and Flashing the Project

Use the "ESP32-IDF: Build, Flash and Monitor" icon located at the bottom of the VS Code window to build and flash the code onto your ESP32 board.

Program Output

After running the program, you will see output in the terminal like this:

Conclusion

In this blog, we demonstrated how to use the ESP-IDF's logging system (esp_log) to manage log outputs and control an LED on the ESP32, while also logging relevant operational messages. With the use of ESP_LOGI(), we can conveniently track the status of the program, which is very useful for debugging and performance monitoring.

By utilizing the logging system, you can flexibly set different log levels to monitor the details of the program's execution at various stages. Hopefully, this helps you better understand the logging feature in ESP32 development!