ESP32 LED blink tutorial using ESP-IDF FreeRTOS framework.

esp32 led blink


ESP32 is an affordable microcontroller that offers built-in WiFi and Bluetooth capabilities. To develop applications for ESP32, we have the option to use either the Arduino framework or the ESP-IDF framework. In this tutorial, we will focus on developing a basic LED blink program using the ESP-IDF framework, which is the officially supported framework for ESP32. For comprehensive information on ESP-IDF you can refer to its official documentation at

https://www.espressif.com/en/products/sdks/esp-idf

First lets create simple project using PlatformIO for ESP32. If you are new to PlatformIO, I have explained how to install PlatformIO with Visual Studio code at https://c2plabs.com/blog/2021/12/14/platformio-installation-with-visual-studio-code-and-hello-world-program/

After blink project is created in platformIO, go to src/main.cpp file and add code for blink LED.

#include <driver/gpio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>

#define LED_PIN 2

void led_blink(void *pvParams) {
    gpio_pad_select_gpio(LED_PIN);
    gpio_set_direction (LED_PIN,GPIO_MODE_OUTPUT);
    while (1) {
        gpio_set_level(LED_PIN,0);
        vTaskDelay(1000/portTICK_RATE_MS);
        gpio_set_level(LED_PIN,1);
        vTaskDelay(1000/portTICK_RATE_MS);
    }
}

void app_main() {
    xTaskCreate(&led_blink,"LED_BLINK",512,NULL,5,NULL);
}

Include the required header files for using ESP32 GPIO and FreeRTOS library. We are using ESP32 nodeMCU board which has on-board LED is connected to GPIO 2, app_main is the first function called by Application startup code in ESP-IDF freeRTOS. ESP-IDF has Application Startup Flow which involves first stage and 2nd stage boot-loaders etc. https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/startup.html has documented Application Startup flow.

In app_main we are creating a freeRTOS task to blink LED at 1 sec delay. xTaskCreate is the freeRTOS call used to create task. This function takes different arguments like taskFunction, name of the task, Stack Size, Parameters to the Task function, priority of this task and handle to the task. This freeRTOS reference can be found at https://www.freertos.org/a00125.html

Let’s look at led_blink task function

gpio_pad_select_gpio: Enable the required GPIO

gpio_set_direction: This function is used to set the GPIO direction input/output, As we are using LED PIN this is set as OUTPUT pin.

gpio_set_level: This function is used to set GPIO to logic high or low.

vTaskDelay: This is the freeRTOS task delay function and delay is expressed in terms of portTICK_RATE_MS