The Complete Guide to ESP32 Development With ESP-IDF
Learn ESP32 firmware with ESP-IDF v5.4: install the toolchain, build a project, use FreeRTOS tasks, GPIO, NVS, Wi-Fi, HTTP, OTA and debugging, with code.

Most people meet the ESP32 through the Arduino IDE, copy a Wi-Fi sketch and have a web server running in ten minutes. That path works until the sketch needs two things at once, a firmware update over the air, a partition for stored settings, or a crash that must be explained. At that point you are using the ESP-IDF underneath without knowing it. ESP-IDF, the Espressif IoT Development Framework, is the vendor's own C framework for the ESP32 family. It contains the FreeRTOS port, the Wi-Fi and Bluetooth stacks, the TCP/IP stack, drivers for every peripheral, the bootloader, and the build system that ties them together. Learning it directly gives you control over all of it.
This guide is a map and a set of worked examples for ESP-IDF v5.4. It starts with what the chips are, installs the tools, builds a first project, and then covers the pieces every real firmware uses: configuration, tasks, GPIO, persistent storage, networking, a web server, over-the-air updates, memory and debugging. Each section carries working code and the log you should expect to see. Where a topic has a full post of its own, the section says what the post will add, and those posts are linked once they are live. If you are coming from Arduino, the closing section explains how the two relate.
Versions used throughout: ESP-IDF v5.4, built with the Xtensa and RISC-V toolchains that install.sh downloads (GCC 14.2 based in v5.4), CMake 3.16 or newer, Ninja, and Python 3.9 or newer. The examples target an ESP32-S3 DevKitC-1 and run on other chips with the target name changed. Flash and RAM sizes quoted come from the datasheets of the named chips.
What the ESP32 family is
"ESP32" is both one chip and a family. The original ESP32 has two Xtensa LX6 cores at up to 240 MHz, Wi-Fi 4 (802.11 b/g/n), classic Bluetooth and Bluetooth Low Energy, 520 KB of internal SRAM, and external flash. Later chips changed the CPU and the radios:
| Chip | CPU | Wi-Fi | Bluetooth | Notable |
|---|---|---|---|---|
| ESP32 | 2 x Xtensa LX6, up to 240 MHz | 802.11 b/g/n | Classic + LE 4.2 | Original, widest library support |
| ESP32-S2 | 1 x Xtensa LX7, up to 240 MHz | 802.11 b/g/n | None | USB OTG, no Bluetooth |
| ESP32-S3 | 2 x Xtensa LX7, up to 240 MHz | 802.11 b/g/n | LE 5 | Vector instructions, USB OTG, octal PSRAM |
| ESP32-C3 | 1 x RISC-V, up to 160 MHz | 802.11 b/g/n | LE 5 | Low cost, RISC-V |
| ESP32-C6 | 1 x RISC-V, up to 160 MHz | 802.11 b/g/n/ax | LE 5 | Wi-Fi 6, 802.15.4 for Thread and Zigbee |
| ESP32-H2 | 1 x RISC-V, up to 96 MHz | None | LE 5 | 802.15.4 only radio side |
Pick the chip from the datasheet, not from the family name. A separate post compares the four chips most new designs choose between. For this guide, the key idea is that ESP-IDF treats the chip as a build target. The same source compiles for several, and idf.py set-target selects one, so code written here is largely portable between them.
An ESP32 module also needs external flash. Boards typically carry 4 MB to 16 MB of SPI flash, and some modules add PSRAM, external RAM in the megabytes, for large buffers. The firmware lives in the flash and is cached into the CPU address space; it executes from flash through a cache rather than from a dedicated code memory. That is why interrupt handlers have attributes for living in IRAM, and why a flash write can stall code that is not cached. A later section returns to memory.
Install the toolchain
ESP-IDF is a Git repository plus a script that installs the compilers and Python tools into a private directory under your home. On Linux and macOS:
mkdir -p ~/esp
cd ~/esp
git clone -b v5.4 --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
./install.sh esp32,esp32s3,esp32c3The argument limits the download to the chips you build for. Leave it out, or pass all, to install every chip's toolchain. The installer creates a Python virtual environment, downloads the cross compilers (Xtensa for ESP32, S2 and S3; RISC-V for the C and H series), OpenOCD, and a CMake and Ninja if your system lacks them.
The installer does not modify your shell. Each terminal where you build must source the export script, which sets IDF_PATH and adds the tools to PATH:
. ~/esp/esp-idf/export.shDetecting the Python interpreter
Checking "python3" ...
Python 3.12.3
"python3" has been detected
Checking Python compatibility
Checking other ESP-IDF version.
Adding ESP-IDF tools to PATH...
Using Python interpreter in /home/dev/.espressif/python_env/idf5.4_py3.12_env/bin/python
Checking if Python packages are up to date...
Python requirements are satisfied.
Done! You can now compile ESP-IDF projects.
Go to the project directory and run:
idf.py buildThe paths in that output differ on your machine. Many people alias the export line as get_idf in their shell profile, because it must be run in every new terminal. On Windows, the ESP-IDF Tools Installer provides a pre-configured command prompt instead. Running idf.py --version afterwards prints the version you sourced, which is the first thing to check when a build behaves strangely:
idf.py --versionESP-IDF v5.4A dedicated post covers installation and the first build step by step, including a Linux serial-port permission problem that stops flashing. Here we keep moving.
The anatomy of a project
An ESP-IDF project is a directory with a top-level CMakeLists.txt and a main component. Components are the unit of code in ESP-IDF, and there is nothing special about main except that it is required and linked into the application. A minimal tree looks like this:
hello/
CMakeLists.txt
main/
CMakeLists.txt
hello_main.c
sdkconfig (generated)
build/ (generated)The top-level file includes ESP-IDF's project CMake and names the project:
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(hello)The component file registers the source files and the include directories:
idf_component_register(SRCS "hello_main.c"
INCLUDE_DIRS ".")The idf_component_register call is the only API a simple component needs. A component can declare REQUIRES for the components whose headers it exposes, and PRIV_REQUIRES for those it uses only internally. Since ESP-IDF v5.0, the main component has common dependencies pulled in by default, so a small program rarely lists any.
Here is the entry point. Unlike a desktop program, there is no main() for you to write. ESP-IDF's startup code initializes the chip, starts FreeRTOS and runs app_main() in a task named main:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_chip_info.h"
#include "esp_system.h"
static const char *TAG = "hello";
void app_main(void)
{
esp_chip_info_t info;
esp_chip_info(&info);
ESP_LOGI(TAG, "chip model %d, %d cores, revision %d",
(int)info.model, info.cores, info.revision);
ESP_LOGI(TAG, "free heap: %lu bytes", (unsigned long)esp_get_free_heap_size());
for (int i = 3; i > 0; i--) {
ESP_LOGI(TAG, "restarting in %d", i);
vTaskDelay(pdMS_TO_TICKS(1000));
}
esp_restart();
}ESP_LOGI writes an informational line with a timestamp and a tag. vTaskDelay puts the task to sleep for a number of ticks; pdMS_TO_TICKS converts milliseconds to ticks using the configured tick rate, which is 100 Hz by default in ESP-IDF, so the smallest sleep is 10 ms. After the countdown, esp_restart() reboots. The log on the serial console looks like this, with a different heap figure and revision on your board:
I (298) hello: chip model 9, 2 cores, revision 2
I (298) hello: free heap: 387204 bytes
I (298) hello: restarting in 3
I (1298) hello: restarting in 2
I (2298) hello: restarting in 1The number in parentheses is milliseconds since boot, and the letter is the log level. The model value 9 is CHIP_ESP32S3 in the esp_chip_model_t enumeration for this release.
Build, flash, monitor
Three commands cover the daily loop. First select the target once per project, because it resets the generated configuration:
idf.py set-target esp32s3
idf.py build
idf.py -p /dev/ttyACM0 flash monitorset-target regenerates sdkconfig with defaults for the chip. build runs CMake and Ninja. flash writes the bootloader, the partition table and the application to the right offsets, and monitor opens a serial terminal that decodes addresses in crash backtraces using the ELF file. Quit the monitor with Ctrl+]. On a DevKitC with a USB-to-serial bridge the port is typically /dev/ttyUSB0 on Linux, and on the S3's built-in USB it is /dev/ttyACM0; on macOS look for /dev/cu.usbmodem*.
The end of a build prints the image size and where the files are:
Project build complete. To flash, run:
idf.py flash
or
idf.py -p PORT flash
or
python -m esptool --chip esp32s3 -b 460800 --before default_reset --after hard_reset write_flash --flash_mode dio --flash_size 2MB --flash_freq 80m 0x0 build/bootloader/bootloader.bin 0x8000 build/partition_table/partition-table.bin 0x10000 build/hello.binThree binaries are flashed. The bootloader goes at 0x0 on the ESP32-S3 (at 0x1000 on the original ESP32), the partition table at 0x8000, and the application at 0x10000 by default. That layout is why a project is more than one file, and why the partition table matters later.
Configuration with menuconfig and sdkconfig
ESP-IDF uses Kconfig, the configuration system from the Linux kernel. idf.py menuconfig opens a terminal menu where you set options such as the flash size, the log level, the FreeRTOS tick rate and the Wi-Fi buffers. Your choices are saved in sdkconfig, and every option becomes a CONFIG_ macro in the generated sdkconfig.h, available in C and in CMake:
#if CONFIG_FREERTOS_HZ == 1000
/* 1 ms ticks */
#endifTreat sdkconfig as a build input that belongs in version control, and keep project-specific defaults in an sdkconfig.defaults file, which is applied before the generated sdkconfig is created. Change a single option in sdkconfig.defaults and delete the build directory's sdkconfig to apply it:
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_FREERTOS_HZ=1000
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
CONFIG_COMPILER_OPTIMIZATION_SIZE=yA separate post covers menuconfig and sdkconfig handling in detail, including CONFIG_ option names for the flash size and partition table, which are the settings people most often get wrong.
FreeRTOS: tasks, queues and the two cores
ESP-IDF runs FreeRTOS, in an SMP port on the dual-core chips. A task is a function with its own stack that the scheduler runs. The main task that calls app_main is just one task and can create more. Create a task with xTaskCreate, or pin it to a core with xTaskCreatePinnedToCore. The stack size argument is in bytes in ESP-IDF, not in words as in vanilla FreeRTOS, which surprises people reading older examples.
Here is a producer and a consumer connected by a queue, a pattern you will use constantly:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"
static const char *TAG = "tasks";
static QueueHandle_t q;
static void producer(void *arg)
{
int value = 0;
for (;;) {
xQueueSend(q, &value, portMAX_DELAY);
value++;
vTaskDelay(pdMS_TO_TICKS(500));
}
}
static void consumer(void *arg)
{
int value;
for (;;) {
if (xQueueReceive(q, &value, portMAX_DELAY) == pdTRUE) {
ESP_LOGI(TAG, "got %d on core %d", value, xPortGetCoreID());
}
}
}
void app_main(void)
{
q = xQueueCreate(8, sizeof(int));
xTaskCreatePinnedToCore(producer, "producer", 2048, NULL, 5, NULL, 0);
xTaskCreatePinnedToCore(consumer, "consumer", 3072, NULL, 5, NULL, 1);
}The producer runs on core 0 and sends an integer every 500 ms. The consumer is on core 1 and blocks on the queue, using no CPU while empty. On a single-core chip such as the ESP32-C3, xTaskCreatePinnedToCore with a core number of 1 fails, and tskNO_AFFINITY or core 0 is correct. The log shows messages crossing the cores:
I (312) tasks: got 0 on core 1
I (812) tasks: got 1 on core 1
I (1312) tasks: got 2 on core 1Two rules prevent most task bugs. Give each task a stack large enough for its deepest call chain, and measure it, because a small stack causes a crash far from the cause; a post on stack sizing with uxTaskGetStackHighWaterMark covers how. And never block forever inside an interrupt handler or a callback of the Wi-Fi and TCP/IP tasks, because those are system tasks you do not own.
Also note the default priorities. ESP-IDF's own system tasks use priorities such as 23 for the Wi-Fi task and 1 for the idle task, so an application task at priority 5 shares the CPU with them in a defined order. A busy loop at a high priority without a delay starves the idle task and trips the task watchdog, which prints a message naming the task that did not yield.
GPIO
The GPIO driver in v5.4 is driver/gpio.h. The recommended pattern is to describe a pin in a gpio_config_t structure and apply it with gpio_config(). The LED on most ESP32-S3 DevKitC-1 boards is a single RGB LED on GPIO 48, so for a plain output use any free pin, and GPIO 2 on many ESP32 boards:
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define LED_PIN GPIO_NUM_2
void app_main(void)
{
gpio_config_t cfg = {
.pin_bit_mask = 1ULL << LED_PIN,
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
ESP_ERROR_CHECK(gpio_config(&cfg));
int level = 0;
for (;;) {
gpio_set_level(LED_PIN, level);
level = !level;
vTaskDelay(pdMS_TO_TICKS(500));
}
}ESP_ERROR_CHECK is ESP-IDF's assertion for esp_err_t results: on a non-zero error code it prints the file, line and error name, then aborts. Use it for calls that cannot fail in a working system, and handle errors explicitly for those that can, such as network operations.
Reading an input with an interrupt follows the same pattern with GPIO_MODE_INPUT and intr_type, after installing the shared interrupt service with gpio_install_isr_service(0) and attaching a handler with gpio_isr_handler_add. Handlers run in interrupt context, so they must not call blocking functions, only the FromISR variants such as xQueueSendFromISR.
Not every pin is free. Some are strapping pins read at boot to choose the boot mode, some are connected to the flash and PSRAM, and on the S3 the USB data pins are GPIO 19 and 20. The datasheet's pin table lists which are safe for general use, and ignoring it is the usual reason a board will not boot after you attach a sensor.
Non-volatile storage
Settings and calibration data need to survive a reboot, and writing raw flash sectors by hand is error-prone. ESP-IDF provides NVS, a key-value store in a dedicated flash partition that handles wear leveling and power-loss safety. Initialize it once at start-up, handling the two errors that a changed partition layout or a new library version can raise:
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
static const char *TAG = "nvs";
void app_main(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
nvs_handle_t h;
ESP_ERROR_CHECK(nvs_open("storage", NVS_READWRITE, &h));
int32_t boots = 0;
err = nvs_get_i32(h, "boots", &boots);
if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
ESP_LOGE(TAG, "read failed: %s", esp_err_to_name(err));
}
boots++;
ESP_ERROR_CHECK(nvs_set_i32(h, "boots", boots));
ESP_ERROR_CHECK(nvs_commit(h));
nvs_close(h);
ESP_LOGI(TAG, "boot count: %ld", (long)boots);
}The namespace storage groups keys. A missing key returns ESP_ERR_NVS_NOT_FOUND, which is the normal first-boot case and not a failure. nvs_commit flushes the pending writes. After three reboots the console shows:
I (301) nvs: boot count: 3Erasing NVS on ESP_ERR_NVS_NO_FREE_PAGES is acceptable during development and destructive in the field, since it discards stored credentials. A product handles it by migrating, and the Wi-Fi driver itself stores its calibration in NVS too, so never erase it without a reason.
Wi-Fi in station mode
Wi-Fi in ESP-IDF is a stack of components: the Wi-Fi driver, the network interface layer esp_netif, the default event loop, and the TCP/IP stack, lwIP. The code follows a fixed order: initialize NVS, the network interface layer and the event loop, create the default station interface, initialize the driver, register for events, configure credentials, and start. Connection progress arrives as events rather than return values.
#include <string.h>
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#define WIFI_SSID "example-network"
#define WIFI_PASS "change-me-please"
#define GOT_IP_BIT BIT0
static const char *TAG = "wifi";
static EventGroupHandle_t s_events;
static void on_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
ESP_LOGW(TAG, "disconnected, retrying");
esp_wifi_connect();
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
ESP_LOGI(TAG, "got ip " IPSTR, IP2STR(&e->ip_info.ip));
xEventGroupSetBits(s_events, GOT_IP_BIT);
}
}
void wifi_start(void)
{
s_events = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &on_event, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &on_event, NULL));
wifi_config_t wc = { 0 };
strncpy((char *)wc.sta.ssid, WIFI_SSID, sizeof(wc.sta.ssid) - 1);
strncpy((char *)wc.sta.password, WIFI_PASS, sizeof(wc.sta.password) - 1);
wc.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wc));
ESP_ERROR_CHECK(esp_wifi_start());
xEventGroupWaitBits(s_events, GOT_IP_BIT, pdFALSE, pdTRUE, portMAX_DELAY);
}
void app_main(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ESP_ERROR_CHECK(nvs_flash_init());
}
wifi_start();
}The order of events is the lesson. esp_wifi_start() raises WIFI_EVENT_STA_START, the handler calls esp_wifi_connect(), association and authentication follow, and once DHCP completes the TCP/IP stack posts IP_EVENT_STA_GOT_IP. Until that event, there is no usable network, even though the Wi-Fi link is up. Waiting on an event-group bit turns the event into something app_main can block on. Example output on a successful run:
I (612) wifi: got ip 192.168.1.42The credentials in source are for the example only. A product reads them from NVS or from provisioning. The retry on disconnect is intentionally simple; a real handler counts attempts and backs off. A dedicated post walks the same flow in more detail, and the networking topics that build on it, MQTT and ESP-NOW, have their own posts.
Serving a web page
Once you have an IP address, the esp_http_server component turns the chip into a small web server. Add esp_http_server to the component requirements, register a URI handler, and start the server:
#include "esp_http_server.h"
static esp_err_t root_get(httpd_req_t *req)
{
const char *body = "<h1>Hello from ESP32</h1>";
httpd_resp_set_type(req, "text/html");
return httpd_resp_send(req, body, HTTPD_RESP_USE_STRLEN);
}
httpd_handle_t web_start(void)
{
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
httpd_handle_t server = NULL;
if (httpd_start(&server, &cfg) == ESP_OK) {
httpd_uri_t root = {
.uri = "/",
.method = HTTP_GET,
.handler = root_get,
.user_ctx = NULL,
};
httpd_register_uri_handler(server, &root);
}
return server;
}The server runs its own task, with a stack size set in httpd_config_t (4096 bytes by default), so a handler that formats large strings on the stack needs cfg.stack_size raised. Requesting http://192.168.1.42/ in a browser returns the heading. A full post builds a page with a form and a JSON endpoint.
Partitions and over-the-air updates
The flash is divided by a partition table, a small CSV that ESP-IDF compiles into a binary at 0x8000. The default single-app table has nvs, phy_init and one factory application partition. A device that must be updated in the field needs two application slots and a small otadata partition recording which one to boot. Declaring that is a CSV file:
nvs, data, nvs, 0x9000, 0x4000,
otadata, data, ota, 0xd000, 0x2000,
phy_init, data, phy, 0xf000, 0x1000,
ota_0, app, ota_0, 0x10000, 0x180000,
ota_1, app, ota_1, 0x190000,0x180000,Point the project at it with CONFIG_PARTITION_TABLE_CUSTOM=y and CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv". The total must fit the flash: this table ends at 0x310000, so a 4 MB part has room to spare. Each application slot has to be at least as large as the biggest image you will ever ship, with margin.
The over-the-air update itself uses the esp_https_ota component, which downloads an image over HTTPS and writes it into the inactive slot:
#include "esp_https_ota.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "esp_system.h"
static const char *TAG = "ota";
extern const char server_cert_pem_start[] asm("_binary_server_cert_pem_start");
void ota_update(void)
{
esp_http_client_config_t http = {
.url = "https://updates.example.test/firmware.bin",
.cert_pem = server_cert_pem_start,
};
esp_https_ota_config_t ota = { .http_config = &http };
esp_err_t err = esp_https_ota(&ota);
if (err == ESP_OK) {
ESP_LOGI(TAG, "update installed, restarting");
esp_restart();
} else {
ESP_LOGE(TAG, "update failed: %s", esp_err_to_name(err));
}
}After a successful write, esp_https_ota marks the new slot as the boot slot, and the next boot runs it. Safe updates also need rollback: enable CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE, and have the new firmware call esp_ota_mark_app_valid_cancel_rollback() only after it has proven itself, for instance after connecting to the network. If it crashes before that call, the bootloader returns to the previous slot on the next reset. Without that call, one bad image bricks a remote device. A separate post designs the partition table and a download-mode recovery path in detail.
Memory: internal RAM, flash cache and PSRAM
An ESP32 has several memory regions with different rules. Instruction and data RAM are internal SRAM, fast and small. Code in flash runs through a cache. Larger buffers can sit in external PSRAM when the module has it, at the cost of access time and some restrictions, such as not being usable for DMA on every chip. The allocator knows about this through capability flags, and heap_caps_malloc lets you ask for a kind of memory:
#include "esp_heap_caps.h"
void *big = heap_caps_malloc(256 * 1024, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (big == NULL) {
/* no PSRAM, or it is full */
}
size_t internal_free = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
size_t spiram_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);Plain malloc returns internal RAM unless you enable PSRAM in menuconfig and choose to let small allocations spill over, so a large buffer can quietly come from the wrong place. The expert posts in this series explain how the address space maps IRAM, DRAM, the flash cache and PSRAM, and show heap_caps use on the S3.
The practical habit is to log the heap at key points. esp_get_free_heap_size() gives the total free, and esp_get_minimum_free_heap_size() gives the lowest it has been since boot, which is the number that predicts a late out-of-memory failure:
ESP_LOGI(TAG, "free %lu, low-water %lu",
(unsigned long)esp_get_free_heap_size(),
(unsigned long)esp_get_minimum_free_heap_size());Logging, panics and debugging
The log library has five levels, error to verbose, set per tag at run time with esp_log_level_set("wifi", ESP_LOG_DEBUG) and capped at build time by CONFIG_LOG_MAXIMUM_LEVEL. Messages above the compile-time level are removed from the binary.
When firmware crashes, ESP-IDF prints a panic report with the exception cause, the registers and a backtrace of addresses. idf.py monitor decodes these addresses against the ELF and prints function names and lines automatically:
Guru Meditation Error: Core 0 panic'ed (LoadProhibited). Exception was unhandled.
Core 0 register dump:
PC : 0x420091a2 PS : 0x00060730 A0 : 0x820094f0 A1 : 0x3fc9a2d0
...
Backtrace: 0x420091a2:0x3fc9a2d0 0x420094ed:0x3fc9a2f0 0x42009c19:0x3fc9a310
#0 0x420091a2 in sensor_read at main/sensor.c:42
#1 0x420094ed in app_main at main/main.c:18A LoadProhibited panic with EXCVADDR near zero is a null pointer dereference. The monitor's decoded lines point at main/sensor.c:42. A post later in this series shows how to decode a backtrace by hand with addr2line when the monitor is not attached. For deeper inspection, the S3 and C-series chips have a built-in USB JTAG interface, so OpenOCD and GDB work over the same cable as flashing, covered in a separate expert post.
Two further tools save time. idf.py size-components prints the flash and RAM used by each library, which tells you where a bloated image comes from. And the core dump feature stores a crash dump in flash for later retrieval, which is the only way to learn about a crash that happened in the field.
Testing without hardware in the loop
Hardware tests need a board, and a lot of firmware logic does not. ESP-IDF supports a Linux target (idf.py --preview set-target linux) that builds a subset of components for the host, so pure logic, parsers and state machines can be unit tested on your laptop with the Unity test framework that ESP-IDF bundles. This guide does not run any code, and neither should you rely on it alone: Unity tests on the host catch logic errors cheaply, and a small number of on-target tests catch the rest.
Power and sleep, in brief
A battery product spends most of its time asleep. The chip offers modem sleep, light sleep and deep sleep. In deep sleep the CPU and most RAM are off, and a wake source such as a timer or a pin restarts the chip from the beginning. Data you must keep goes into NVS or into RTC memory, marked with RTC_DATA_ATTR:
#include "esp_sleep.h"
RTC_DATA_ATTR static int wake_count;
void app_main(void)
{
wake_count++;
/* ... read a sensor, send it, then sleep for 60 seconds ... */
esp_sleep_enable_timer_wakeup(60ULL * 1000000ULL);
esp_deep_sleep_start();
}The argument to the wake-up timer is in microseconds. wake_count survives deep sleep and resets on a power cycle. Every Wi-Fi connection costs energy, so a design that wakes, connects, sends and sleeps spends most of its energy in the connect step, a reason to cache the access-point channel and BSSID.
Components and the component manager
ESP-IDF's own libraries are components, and you can add more. The IDF Component Manager downloads components from the registry, listed in an idf_component.yml file in your component:
dependencies:
idf: ">=5.4"
espressif/led_strip: "^3.0.0"The next idf.py build fetches the dependency into managed_components/, pinned in dependencies.lock. Commit the lock file and not the managed folder. A reusable component of your own has the same manifest, which a separate post covers.
Putting a project together
A tidy first real project has these parts, in this order of work:
Generate the project skeleton and select the target with
idf.py set-target.Put the settings that differ from defaults in
sdkconfig.defaultsand commit it.Split code into components by responsibility: one for the sensor, one for the network, one for the application logic, each with its own
CMakeLists.txtand clearREQUIRES.Decide the partition table at the start, because changing it later means a full re-flash of every device.
Add logging with a tag per component, so output can be filtered with
esp_log_level_set.Add rollback-capable OTA before the first device leaves your desk.
Writing events between components through the default event loop keeps them decoupled; a post on the event library shows how to define your own event base and post to it from any task.
Who this guide does not fit
People building a single throwaway prototype. If the goal is a blinking LED and a web page in an afternoon, the Arduino core on the ESP32 gets there faster, and you can move to ESP-IDF later because the Arduino core itself is built on it as a component.
Teams that need a certified RTOS or safety case. ESP-IDF's FreeRTOS port and drivers are not a safety-certified product. If your system needs one, you need a different platform and a different guide.
Developers who need a full Linux. The ESP32 runs an RTOS with no memory protection between tasks on most chips, and no virtual memory. If you want processes, a file system with permissions and standard sockets across an MMU, choose an SoC that runs Linux.
Projects that need the lowest possible sleep current without radio. An ESP32's deep sleep is low, but a dedicated low-power microcontroller or a chip designed around a sub-microamp sleep state can do better. Read the datasheet's current tables for the actual modes before committing.
From Arduino to ESP-IDF
The Arduino core for ESP32 is a library that sits on top of ESP-IDF. setup() and loop() are called from an ESP-IDF task, digitalWrite calls the same GPIO driver, and WiFi.begin() wraps the esp_wifi calls above. Three things change when you drop it. You write app_main and create your own tasks. Configuration moves from board menus to menuconfig. And libraries become components with a CMakeLists.txt instead of a folder dropped into libraries/. The reward is access to everything the Arduino layer hides: partition tables, rollback, the event loop, power management and the low-level drivers. You can also mix the two, by using Arduino as an ESP-IDF component, which is the supported migration path.
Where to go next
The posts around this guide go deeper on each part. The installation post covers idf.py and serial-port problems. A pair of posts covers configuration and partition design. Networking posts cover Wi-Fi station mode, the HTTP server, MQTT and ESP-NOW. Task and memory posts cover stack sizing, heap_caps and PSRAM, and the memory map. The debugging posts cover backtraces and JTAG, and the size post shrinks the binary. Read them in that order if you are new, and jump to the one that matches the problem in front of you if you are not.
Your own events with the default event loop
The default event loop that Wi-Fi uses is available to your code, and it is the cleanest way to keep components apart. A component defines an event base and a set of event ids, posts to the loop when something happens, and any other component registers a handler without the first one knowing it exists. The sensor component never includes a header from the display component.
#pragma once
#include "esp_event.h"
ESP_EVENT_DECLARE_BASE(APP_EVENT);
typedef enum {
APP_EVENT_TEMPERATURE,
APP_EVENT_BUTTON,
} app_event_id_t;
typedef struct {
float celsius;
} app_temperature_t;#include "app_events.h"
ESP_EVENT_DEFINE_BASE(APP_EVENT);The producer posts a copy of the payload, so it can be a stack variable. The handler runs in the loop's task, which is a shared resource, so handlers must be short:
#include "esp_log.h"
#include "app_events.h"
static const char *TAG = "events";
static void on_temperature(void *arg, esp_event_base_t base, int32_t id, void *data)
{
const app_temperature_t *t = (const app_temperature_t *)data;
ESP_LOGI(TAG, "temperature %.1f C", t->celsius);
}
void events_demo(void)
{
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_event_handler_register(APP_EVENT, APP_EVENT_TEMPERATURE,
on_temperature, NULL));
app_temperature_t t = { .celsius = 21.5f };
ESP_ERROR_CHECK(esp_event_post(APP_EVENT, APP_EVENT_TEMPERATURE, &t, sizeof(t),
portMAX_DELAY));
}I (352) events: temperature 21.5 CIf the loop is already created by the Wi-Fi code, the second esp_event_loop_create_default() returns ESP_ERR_INVALID_STATE, so create it once, early, and check for that code in shared start-up helpers. A dedicated post goes through custom loops with their own task and queue size, which you want when a handler might block.
Security you should decide before shipping
An ESP32 stores its firmware in external flash, which anyone with physical access can read. Two features address that, and both are one-way decisions once enabled on a device.
Secure Boot verifies a signature on the bootloader and the application before running them, so only firmware signed with your private key boots. Flash Encryption encrypts the contents of the flash with a key stored in eFuses, so a dump of the chip is useless without the key. The details differ between chip generations: the original ESP32 uses Secure Boot v1 or v2 depending on the revision, and the newer chips use Secure Boot v2 with RSA or ECDSA signatures. Check the "Security" chapter of the Technical Reference Manual for your chip before you plan the production flow.
The practical points are these. eFuses are write-once, so a mistake in the key or the configuration cannot be undone on that chip. Development mode lets you test the flow with reflashable settings, and release mode burns the fuses that lock it down. OTA updates under Flash Encryption work, because the bootloader decrypts on read and the OTA component writes encrypted data when it is enabled, but you must test that path before burning the release fuses. And NVS can be encrypted separately, with its own key partition, which protects stored credentials even when full flash encryption is not used.
A short field manual of failures
These are the problems new ESP-IDF users meet most often, with the literal text of the message and the cause.
Failed to connect to ESP32: Wrong boot mode detected. The tool could not put the chip into download mode. On boards without auto-reset circuitry, hold the BOOT button while pressing RESET, then release BOOT. A dedicated post covers the circuit behind this and the manual sequence.
**E (305) flash_parts: partition 0 invalid magic number 0xffff.** The bootloader found no partition table at 0x8000. Either the table was never flashed, or the flash size in the configuration is smaller than the offsets used. Run idf.py partition-table-flash or a full flash, and confirm CONFIG_ESPTOOLPY_FLASHSIZE.
**Guru Meditation Error: Core 0 panic'ed (Stack protection fault) or Stack overflow in task.** A task's stack is too small. Raise the size passed to xTaskCreate, then measure with uxTaskGetStackHighWaterMark and leave margin.
**Task watchdog got triggered.** A task that was subscribed to the task watchdog, or the idle task on a core, did not run within the timeout. A busy loop without a delay at a priority above idle is the usual reason. Add vTaskDelay, or lower the priority.
**wifi:Association refused temporarily or repeated disconnects.** Often a weak signal, an access point that rejects the security mode, or WPA3-only transition settings. Check wc.sta.threshold.authmode against the access point's mode.
**ESP_ERR_NVS_NO_FREE_PAGES.** The NVS partition is full or its format changed. The start-up code in this guide handles it by erasing, which is fine in development.
Heap exhaustion that appears after hours. A leak, or fragmentation from repeated large allocations. Log esp_get_minimum_free_heap_size() periodically and enable heap tracing in menuconfig to find the allocation site.
Each of these has a short path to a cause once you know the layer that raised it: the tool (esptool), the bootloader (flash_parts), FreeRTOS (stack and watchdog), or a subsystem log tag (wifi, nvs).
Choosing a chip, once you know what you build
With the framework understood, the chip choice becomes a requirements list. Count the radios first: Bluetooth classic is only on the original ESP32, Wi-Fi 6 and 802.15.4 for Thread are on the C6, and the S2 has no Bluetooth. Check the core count for work that must not be preempted by the radio stack, because pinning your time-critical task to the core the Wi-Fi task does not use is the usual answer on a dual-core part. Check the memory: PSRAM interfaces differ (quad on the original and S2, octal on some S3 modules), and external RAM bandwidth is lower than internal. And check the package and pin count against your peripherals, since the C3 and C6 have fewer GPIOs than the S3.
Then choose the module, not the bare chip, unless volume justifies a custom board. Espressif's pre-certified modules carry the antenna and the flash, and radio certification is the expensive part of a product.
Core dumps and the panic handler settings
By default a panic prints its report and reboots, which is useless for a device installed somewhere you cannot reach. Two settings change that. CONFIG_ESP_SYSTEM_PANIC chooses what happens after the report: print and reboot, print and halt for a debugger, or print and enter GDB stub mode. And CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH writes a core dump to a dedicated partition, which you add to the partition table:
coredump, data, coredump, 0x310000, 0x10000,After a crash, the dump stays in flash across the reboot. You retrieve and decode it from a connected host with idf.py coredump-info, which loads the matching ELF from the build directory and prints the same register state and backtrace you would have seen live. The ELF must be the exact one that was flashed, so keep it as a build artifact for every released version, named by the version string in the application descriptor.
A small habit makes crash reports far more useful: set the project version in CMakeLists.txt or with git describe, because ESP-IDF stores it in the application descriptor, and log it at boot. A report that says which build crashed is a report you can reproduce.
Choosing log levels so output stays useful
Logging costs time and flash. Each ESP_LOGI call formats text over the console UART or USB, which is slow compared to the CPU, and a chatty task can delay time-critical work. Set the default level to info in production, keep debug messages in the code, and raise a single tag at run time while investigating with esp_log_level_set("sensor", ESP_LOG_DEBUG). Messages whose level is above CONFIG_LOG_MAXIMUM_LEVEL are compiled out entirely, so you can leave debug statements in hot paths and still ship without paying for them.


