Skip to content
systemcoding.dev
RTOS

Read the current core number with xPortGetCoreID on ESP32

Read the running core with xPortGetCoreID in an ESP-IDF 5 task pinned with xTaskCreatePinnedToCore, instead of assuming core 0.

1 min read
Summarize in AI

ESP-IDF's FreeRTOS runs symmetric tasks across the two cores of an ESP32, and xPortGetCoreID() returns the number of the core executing the caller. It is the quickest way to confirm that pinning did what you meant, and to tag log lines with a core. In ESP-IDF 5.x, xTaskCreatePinnedToCore() takes the stack size in bytes and a core number as its last argument before the handle.

core_id.cc
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdio.h>

static void worker(void *arg)
{
    printf("worker on core %d\n", (int) xPortGetCoreID());
    vTaskDelete(NULL);
}

void app_main(void)
{
    xTaskCreatePinnedToCore(worker, "worker", 2048, NULL, 5, NULL, 1);
}
Text
worker on core 1

The answer is only stable for a pinned task. An unpinned task, created with tskNO_AFFINITY or the plain xTaskCreate(), can be moved between cores by the scheduler, so a core number read at the top of a loop can be stale a microsecond later. For a data structure that must be touched by one core only, pin the task. On a single-core variant such as the ESP32-S2 the function returns 0 and a pin to core 1 is an error. Written for ESP-IDF 5.x, whose FreeRTOS port is described in the ESP-IDF FreeRTOS SMP notes.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.