1  Development environment and ESP-IDF basics

1.1 ESP32-C3

The ESP32-C3 is a Wi-Fi + BLE microcontroller from Espressif Systems.

Item Details
CPU 32-bit RISC-V single core, up to 160 MHz
Memory SRAM 400 KB; flash depends on the module/board (4 MB on the XIAO ESP32C3)
Radio Wi-Fi 4 (2.4 GHz), Bluetooth 5 (LE). Bluetooth Classic is not supported
USB Built-in USB Serial/JTAG (flashing, logging and debugging without a USB-UART bridge chip)

Despite the shared ESP32 name, the original ESP32 has an Xtensa core and also supports Bluetooth Classic, whereas the C3 has a RISC-V core and is BLE-only. On top of ESP-IDF, BLE code can be written almost identically.

WarningAttach the antenna to the XIAO ESP32C3

The Seeed Studio XIAO ESP32C3 has no antenna on the board and is designed to use the supplied external antenna (U.FL connector). Running it without one causes symptoms such as not appearing in scans or dropping the connection at just a few tens of centimetres.

1.2 What is ESP-IDF?

ESP-IDF (Espressif IoT Development Framework) is Espressif’s official development framework. The Arduino ESP32 core also uses ESP-IDF internally.

flowchart TB
  APP["Application (the main/ code you write in this hands-on)"]
  NIM["NimBLE host (the BLE protocol stack)"]
  IDF["ESP-IDF components<br/>(nvs_flash, esp_timer, esp_log ...)"]
  RTOS["FreeRTOS (tasks, queues, timers)"]
  CTRL["BLE controller (binary provided by Espressif)"]
  HW["ESP32-C3 hardware (radio)"]
  APP --> NIM --> CTRL --> HW
  APP --> IDF --> RTOS --> HW
  NIM --> RTOS

Major differences from Arduino:

Arduino ESP-IDF
Entry point setup() and loop() app_main() (it may return; other tasks keep running after it returns)
Build Arduino IDE / PlatformIO CMake + Ninja (wrapped by the idf.py command)
Configuration Almost none sdkconfig (Kconfig). Whether to use BLE is also decided here
Building blocks Libraries Components (registered with CMake per components/ or main/ unit)
OS Hidden FreeRTOS is assumed. You use tasks, queues and timers directly

1.3 Installing ESP-IDF

This hands-on has been verified with ESP-IDF v6.0.1. There are two ways to install it.

1.3.2 Using the command line

If you install with the ESP-IDF Installation Manager (EIM) or similar, ESP-IDF and its tools go under ~/.espressif/. Each time you open a terminal, source the script that activates the environment.

# macOS / Linux (bash / zsh). Adjust the path to your install location
source ~/.espressif/tools/activate_idf_v6.0.1.sh

# check
idf.py --version
TipEither way it’s the same underneath

The VS Code buttons also call idf.py behind the scenes. The explanations below are written with idf.py commands, but feel free to substitute the VS Code buttons.

1.4 Getting the samples

Extracting firmware.zip gives you the following folders.

firmware/
├── step1_hello/          Ch. 1   just prints logs
├── step2_advertise/      Ch. 5   advertising
├── step3_notify/         Ch. 6   GATT service and Notify
├── step4_command/        Ch. 7   commands and responses
├── step5_pairing/        Ch. 9   passkey pairing
└── step6_event_driven/   Ch. 10  event-driven structure (final form)

Each step is an independent ESP-IDF project. In VS Code, open the step’s folder (e.g. step1_hello) as a folder.

1.5 Project structure

Taking Step 1 as an example, let’s look at the minimal structure of an ESP-IDF project.

step1_hello/
├── CMakeLists.txt        definition of the whole project
├── sdkconfig.defaults    initial configuration values (you write this)
└── main/
    ├── CMakeLists.txt    definition of the main component
    └── main.c            where you write app_main()

Building automatically creates the following (neither is included in the distribution).

  • build/ — build artifacts
  • sdkconfig — the actual values of all configuration items. Generated from sdkconfig.defaults and the defaults

1.5.1 Top-level CMakeLists.txt

# Boilerplate for an ESP-IDF project (don't change the order of these 3 lines)
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(step1_hello)

These three lines are boilerplate for an ESP-IDF project. The name in project() becomes the output file name (build/step1_hello.bin).

1.5.2 main/CMakeLists.txt

idf_component_register(SRCS "main.c"
                    INCLUDE_DIRS ".")

idf_component_register() registers this component’s source files and header search paths. From Step 2 on, where BLE is used, you also list the components it depends on, like this.

idf_component_register(SRCS "main.c"
                    INCLUDE_DIRS "."
                    PRIV_REQUIRES bt nvs_flash esp_timer)

Only the headers of components listed in PRIV_REQUIRES can be #included (bt = Bluetooth, nvs_flash = non-volatile storage, esp_timer = high-resolution timer).

1.5.3 sdkconfig.defaults

CONFIG_IDF_TARGET="esp32c3"

Step 1 specifies only the target (the chip type). In steps that use BLE, settings that enable Bluetooth are added here (Chapter 4).

1.6 Step 1: Hello ESP-IDF

/*
 * Step 1: Hello ESP-IDF
 *
 * - starts from app_main()
 * - prints logs to serial with ESP_LOGI
 * - waits 1 second with vTaskDelay (the CPU is yielded to other tasks while waiting)
 */
#include <stdint.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_chip_info.h"

#define TAG "STEP1"

void app_main(void)
{
    esp_chip_info_t chip;
    esp_chip_info(&chip);
    ESP_LOGI(TAG, "Hello ESP-IDF! cores=%d revision=%d", chip.cores, chip.revision);

    uint32_t count = 0;
    while (1) {
        ESP_LOGI(TAG, "count = %lu", (unsigned long)count);
        count++;

        // wait 1000 ms. Spinning without waiting makes the task watchdog warn
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}
  • app_main() is called inside the main task after ESP-IDF has finished booting
  • ESP_LOGI(TAG, ...) outputs a log. I stands for Info; there are also ESP_LOGE (Error), ESP_LOGW (Warning), ESP_LOGD (Debug) and so on. A timestamp and the tag are added automatically
  • vTaskDelay() is the FreeRTOS function “let this task rest for the specified time”. pdMS_TO_TICKS(1000) converts 1000 ms to a number of ticks
NoteIf you don’t wait inside while (1)

FreeRTOS has a task watchdog that watches whether any task is hogging the CPU. If you loop forever without vTaskDelay(), the idle task cannot run and after a few seconds you get the warning task_wdt: Task watchdog got triggered. Unlike Arduino’s loop(), the basic rule is give the CPU back to the OS when you wait.

1.6.1 Build, flash, monitor

cd firmware/step1_hello
idf.py set-target esp32c3     # first time only; creates sdkconfig
idf.py build                  # build
idf.py -p PORT flash monitor  # flash, then open the serial monitor

PORT is a name like /dev/tty.usbmodem* on macOS, /dev/ttyACM0 on Linux, or COM3 on Windows. To leave the monitor press Ctrl + ].

If logs appear every second like this, you have succeeded.

I (285) STEP1: Hello ESP-IDF! cores=1 revision=4
I (285) STEP1: count = 0
I (1285) STEP1: count = 1
I (2285) STEP1: count = 2

The number in parentheses is the elapsed time since boot [ms] (the numbers and revision differ by board).

TipIf flashing fails

The ESP32-C3 normally enters download mode automatically via USB Serial/JTAG. If it still fails, hold the BOOT button, press and release the RESET button, then release BOOT and flash again. After flashing, press the RESET button to return to normal boot.

1.7 Frequently used idf.py commands

Command Description
idf.py set-target esp32c3 Set the target (recreates sdkconfig and build/)
idf.py build Build
idf.py -p PORT flash Flash
idf.py -p PORT monitor Serial monitor (exit with Ctrl + ])
idf.py menuconfig Configuration screen (edit sdkconfig interactively)
idf.py fullclean Delete build/
idf.py -p PORT erase-flash Erase the entire flash (bonding information saved in NVS is erased too)
idf.py size Memory usage overview
ImportantKey points
  • The entry point of ESP-IDF is app_main(). FreeRTOS runs behind the scenes
  • Configuration is sdkconfig. What you write yourself is sdkconfig.defaults
  • Components are registered with idf_component_register(), and what you use goes in PRIV_REQUIRES
  • Inside loops, wait and give the CPU back with vTaskDelay() etc.