Guides · 13 min read

ESP32 FreeRTOS: Dual Core, Tasks, Queues and Semaphores

ESP32 FreeRTOS: xTaskCreatePinnedToCore, priorities, delay vs vTaskDelay, queues, semaphores, stack and watchdog; run an LED, sensor and web server at once.

ESP32 FreeRTOS is the real-time operating system that already runs inside the ESP32 and lets you do several things at once. Every ESP32 sketch you write in the Arduino IDE actually runs on top of FreeRTOS: your setup() and loop() functions run inside a task called loopTask on one of the ESP32's two cores. By creating your own tasks you can blink an LED while reading a sensor and answer web server requests at the same time, and none of them holds up the others. The "several jobs at once" pattern you try to build with millis() on an Arduino Uno gets a much cleaner structure on the ESP32.

In this guide you will learn how the ESP32's two cores are shared and which core Wi-Fi runs on. Then we will create tasks with xTaskCreatePinnedToCore, pin tasks to a specific core, set priorities and see the difference between delay() and vTaskDelay(). We will use a queue to share data safely between tasks, a semaphore to wake a task from a button interrupt and a mutex to protect the shared Serial Monitor. After covering stack size and watchdog errors, we will build a complete example that runs an LED, a sensor and a web server at the same time. At the end there is a short comparison with the two cores of the Raspberry Pi Pico.

ESP32 development board
The classic ESP32 has two Xtensa LX6 cores and can run separate tasks on each with FreeRTOS.

What is ESP32 FreeRTOS and how do the two cores work?

In FreeRTOS every job is a task. A task is an ordinary C function with its own stack memory and priority, usually containing an endless loop. On each core the FreeRTOS scheduler picks the highest-priority task among those ready to run. When a task waits with vTaskDelay(), waits for data from a queue or waits for a semaphore, the core is handed to another task right away. Tasks with the same priority take turns on every tick. In the ESP32 Arduino core a tick is 1 ms (1000 ticks per second), so vTaskDelay(100) waits about 100 ms. The classic ESP32 has two cores: core 0 (PRO_CPU) and core 1 (APP_CPU). Espressif puts wireless communication on core 0 and your code on core 1, so Wi-Fi work does not interrupt your loop. With the default Arduino settings, this is what runs on the cores:

TaskCorePriorityJob
loopTask (setup and loop)11Your Arduino code, 8192-byte stack
Wi-Fi driver023Radio and Wi-Fi protocol
lwIP (tcpip)018TCP/IP stack, web and MQTT packets
Bluetooth (BT/BLE)0HighBluetooth controller and Bluedroid
esp_timer022Software timers
IDLE0 and IDLE10 and 10Idle tasks; feed the watchdog and free the memory of deleted tasks

There are two important lessons in this table. First, the Wi-Fi and TCP/IP tasks have very high priority; if you put a heavy task of your own on core 0, they will interrupt it whenever network traffic arrives, and if your task keeps them busy for long, Wi-Fi suffers. Second, loopTask has a priority of only 1; if you put a higher-priority task on core 1 that never waits, loop() will never run. The ESP32-S3 is also dual-core. The ESP32-S2, ESP32-C3 and ESP32-C6 are single-core; you can still create tasks on these boards, but they all share the same core.

Wiring

For the examples in this article you need an ESP32 DevKit, two LEDs, a potentiometer and a push button. The blue LED on the board is on GPIO 2; connect the second LED to GPIO 4 through a 220 Ω resistor. We connect the potentiometer to GPIO 34, an ADC1 channel, because ADC2 pins cannot be read while Wi-Fi is on.

PartESP32 pinNote
Onboard LEDGPIO 2Built into most DevKits
Second LEDGPIO 4220 Ω series resistor, short leg to GND
Potentiometer wiperGPIO 34Input only, ADC1; outer legs to 3V3 and GND
ButtonGPIO 27Other leg to GND, used with INPUT_PULLUP
Connect the potentiometer's outer leg to 3V3, not 5V. The ESP32's pins work at 3.3 V and are not 5 V tolerant. In projects that use Wi-Fi, connect analog sensors to the ADC1 pins GPIO 32–39; the ADC2 pins (GPIO 0, 2, 4, 12–15, 25–27) cannot be read with analogRead() while Wi-Fi is on. You can check your pin choice in the Pinout tool.

First tasks with xTaskCreatePinnedToCore

In the first example we blink two LEDs with two separate tasks, at different speeds and on different cores. Every task function has the form void function(void *parameter) and contains an endless loop. xTaskCreatePinnedToCore(), which starts the task, also tells it which core to run on. Notice that we use the same task function twice and pass a different settings structure each time; thanks to the parameter, one function drives two LEDs independently.

C++ (Arduino IDE)
1// İki LED, iki görev, iki çekirdek / two LEDs, two tasks, two cores
2struct LedAyari {
3  int pin;          // LED pini / LED pin
4  int beklemeMs;    // yarım periyot / half period
5};
6
7LedAyari led1 = {2, 250};   // dahili LED, hızlı / onboard LED, fast
8LedAyari led2 = {4, 700};   // harici LED, yavaş / external LED, slow
9
10void ledGorevi(void *parametre) {
11  LedAyari *ayar = (LedAyari *)parametre;
12  pinMode(ayar->pin, OUTPUT);
13  for (;;) {                                         // görev asla bitmez / a task never returns
14    digitalWrite(ayar->pin, !digitalRead(ayar->pin));
15    vTaskDelay(pdMS_TO_TICKS(ayar->beklemeMs));      // çekirdeği bırak / give the core away
16  }
17}
18
19void setup() {
20  Serial.begin(115200);
21  // fonksiyon, ad, yığın (bayt), parametre, öncelik, tutamaç, çekirdek
22  // function, name, stack (bytes), parameter, priority, handle, core
23  xTaskCreatePinnedToCore(ledGorevi, "LED1", 2048, &led1, 1, NULL, 0);
24  xTaskCreatePinnedToCore(ledGorevi, "LED2", 2048, &led2, 1, NULL, 1);
25}
26
27void loop() {
28  Serial.printf("loop() cekirdek / core: %d\n", xPortGetCoreID());
29  delay(1000);                                       // ESP32'de delay de çekirdeği bırakır / delay yields on ESP32 too
30}

When you upload the code the two LEDs blink independently, and the Serial Monitor shows that loop() runs on core 1. These are the function's parameters:

ParameterValue in the exampleMeaning
pvTaskCodeledGoreviThe function the task runs
pcName"LED1"Name shown when debugging, up to 16 characters
usStackDepth2048Stack size; on the ESP32 it is in bytes
pvParameters&led1Pointer passed to the task; it should point to a global or static variable
uxPriority1Priority, from 0 (lowest) to 24
pvCreatedTaskNULLHandle for stopping or monitoring the task later
xCoreID0 or 1Core to run on; with tskNO_AFFINITY it runs on whichever core is free
A task function must never end with return; if it does, the ESP32 reports an error and restarts. If a task has finished its work, delete it by calling vTaskDelete(NULL) on the last line. Also do not pass the address of a local variable inside setup() as the task parameter: when setup() ends that variable disappears and the task reads a broken address. On the single-core ESP32-C3, S2 and C6 only 0 or tskNO_AFFINITY can be used as the core number; the most portable option is xTaskCreate(), which does not choose a core.

delay(), vTaskDelay() and vTaskDelayUntil() compared

On an Arduino Uno delay() keeps the processor completely busy; nothing else runs while it waits. On the ESP32 things are different: delay() in the Arduino core actually calls vTaskDelay(). So when you write delay(100) your task sleeps for 100 ms and the core goes to other tasks in the meantime. That is why using delay() inside tasks also works; still, writing vTaskDelay(pdMS_TO_TICKS(100)) in FreeRTOS code shows your intent more clearly. The real difference lies in methods that wait by keeping the processor busy: delayMicroseconds() and empty loops such as while (millis() - t < 500) {} never release the core. We cover the millis() pattern on Arduino in detail in millis() vs delay().

MethodReleases the core?When to use it
delay(ms)Yes (calls vTaskDelay on the ESP32)Simple waits, inside loop()
vTaskDelay(pdMS_TO_TICKS(ms))YesWaiting in tasks; the delay is added to the work time
vTaskDelayUntil(&last, period)YesFixed-rate sampling; exact period regardless of work time
delayMicroseconds(us)NoMicrosecond waits in sensor protocols
while (millis() - t < ms) {}NoDo not use in FreeRTOS tasks; it starves other tasks

If a loop runs with vTaskDelay(100) and the work takes 15 ms, the loop repeats every 115 ms and the error builds up over time. If you want to read a sensor exactly every 100 ms, use vTaskDelayUntil(): the function keeps track of the previous wake-up time and wakes the task exactly one period later each time. The sensor task in the next section uses this method.

Task priorities: which task runs first?

If several tasks on a core are ready to run, the one with the highest priority always runs. A lower-priority task gets the core only when the higher-priority ones are waiting. This is called preemptive priority-based scheduling: as soon as the data a high-priority task is waiting for arrives, the lower-priority task is interrupted. This lets you make jobs that need a fast response high-priority, but there is a trap: if a high-priority task never waits, the tasks below it never run. In practice the following scheme works well:

  • Priority 1: Jobs that are not in a hurry, such as updating a display, writing to the Serial Monitor or a web server. loop() is also at this level.
  • Priority 2–3: Jobs that must be done on time, such as regular sensor reads, control loops and button handling.
  • Priority 4–5: Short tasks woken by an interrupt that must respond immediately.
  • Avoid: Do not give your own tasks priority 18 or higher; those levels belong to Wi-Fi, TCP/IP and the system timers.

Sharing data safely between tasks with a queue

The first idea for moving data between tasks is a global variable, but two tasks can access the same variable at the same time. If one task reads a multi-byte structure while another is writing it, it gets a value that is half old and half new; because such bugs show up rarely and at random, they are very hard to track down. The FreeRTOS solution is the queue. A queue is a line of fixed-size items that moves data by copying it: the sending task leaves a copy with xQueueSend() and the receiving task takes that copy with xQueueReceive(). If the queue is empty, the receiving task sleeps and uses no CPU time; it wakes up as soon as data arrives. In the example below one task reads the potentiometer exactly every 100 ms and puts the reading in the queue together with a timestamp; a second task processes every reading that comes out of the queue.

C++ (Arduino IDE)
1// Sensör görevi -> kuyruk -> işleyici görev / sensor task -> queue -> consumer task
2const int POT_PIN = 34;                 // ADC1 pini / ADC1 pin
3
4struct Olcum {
5  uint16_t ham;                         // 0-4095 ham değer / raw value
6  float volt;                           // gerilim / voltage
7  uint32_t zaman;                       // ms cinsinden zaman / timestamp in ms
8};
9
10QueueHandle_t olcumKuyrugu;
11
12void sensorGorevi(void *parametre) {
13  TickType_t sonUyanma = xTaskGetTickCount();
14  for (;;) {
15    Olcum o;
16    o.ham = analogRead(POT_PIN);
17    o.volt = analogReadMilliVolts(POT_PIN) / 1000.0f;
18    o.zaman = millis();
19    if (xQueueSend(olcumKuyrugu, &o, 0) != pdPASS) {   // kuyruk doluysa bekleme / don't wait if full
20      Serial.println("Kuyruk dolu / Queue full");
21    }
22    vTaskDelayUntil(&sonUyanma, pdMS_TO_TICKS(100));   // tam 100 ms periyot / exact 100 ms period
23  }
24}
25
26void isleyiciGorev(void *parametre) {
27  Olcum o;
28  for (;;) {
29    // veri gelene kadar uyu / sleep until data arrives
30    if (xQueueReceive(olcumKuyrugu, &o, portMAX_DELAY) == pdPASS) {
31      Serial.printf("%lu ms  ham/raw: %4u  %.2f V  bekleyen/waiting: %u\n",
32                    (unsigned long)o.zaman, o.ham, o.volt,
33                    (unsigned)uxQueueMessagesWaiting(olcumKuyrugu));
34    }
35  }
36}
37
38void setup() {
39  Serial.begin(115200);
40  olcumKuyrugu = xQueueCreate(10, sizeof(Olcum));      // 10 ölçümlük kuyruk / queue of 10 readings
41  if (olcumKuyrugu == NULL) {
42    Serial.println("Kuyruk olusturulamadi / Queue creation failed");
43    return;
44  }
45  xTaskCreatePinnedToCore(sensorGorevi, "Sensor", 3072, NULL, 2, NULL, 1);
46  xTaskCreatePinnedToCore(isleyiciGorev, "Isleyici", 3072, NULL, 1, NULL, 1);
47}
48
49void loop() {
50  vTaskDelay(pdMS_TO_TICKS(1000));     // loop'un burada işi yok / loop has nothing to do here
51}

Because the sensor task's priority (2) is higher than the consumer's (1), readings are always taken on time. Even if the consumer slows down for a moment, for example while writing to an SD card, no readings are lost; they wait their turn in the 10-item queue. If the queue fills up, xQueueSend() returns an error without waiting, so you notice it. If you only need the latest value, for example to show the current temperature on a display, you can create a single-item queue, write to it with xQueueOverwrite() and read the value without removing it using xQueuePeek(). We will use this method in the final example.

Semaphores and mutexes: waking a task from an interrupt and protecting a shared resource

A binary semaphore is like a flag that lets a task wait for an event. Its most common use is with interrupts: a button interrupt routine (ISR) must be very short, so it does not do the real work, it only gives the semaphore; the task waiting for that semaphore wakes up and does the job. We explained the basics of interrupts in the Arduino interrupt article. A mutex guarantees that only one task at a time uses a shared resource such as the serial port, the I2C bus or a display. If two tasks call Serial.printf() at the same moment, their lines can get mixed up; with a mutex each task takes the lock before writing and releases it when done. In the code below every button press toggles the second LED, and two tasks write to the same Serial Monitor without mixing their output.

C++ (Arduino IDE)
1const int BUTON_PIN = 27;              // butonun diğer ucu GND / other leg to GND
2const int LED_PIN   = 4;
3
4SemaphoreHandle_t butonSemaforu;       // kesme -> görev sinyali / ISR -> task signal
5SemaphoreHandle_t seriKilit;           // Serial için mutex / mutex for Serial
6
7void IRAM_ATTR butonKesmesi() {
8  BaseType_t uyandir = pdFALSE;
9  xSemaphoreGiveFromISR(butonSemaforu, &uyandir);   // ISR'de FromISR sürümü / FromISR version in ISR
10  if (uyandir == pdTRUE) {
11    portYIELD_FROM_ISR();              // bekleyen görevi hemen çalıştır / run the waiting task now
12  }
13}
14
15void guvenliYaz(const char *metin) {
16  if (xSemaphoreTake(seriKilit, pdMS_TO_TICKS(100)) == pdTRUE) {
17    Serial.println(metin);
18    xSemaphoreGive(seriKilit);         // kilidi mutlaka bırak / always release the lock
19  }
20}
21
22void butonGorevi(void *parametre) {
23  uint32_t sonBasma = 0;
24  for (;;) {
25    xSemaphoreTake(butonSemaforu, portMAX_DELAY);    // basılana kadar uyu / sleep until pressed
26    if (millis() - sonBasma > 200) {                 // 200 ms ark önleme / 200 ms debounce
27      sonBasma = millis();
28      digitalWrite(LED_PIN, !digitalRead(LED_PIN));
29      guvenliYaz("Butona basildi / Button pressed");
30    }
31  }
32}
33
34void raporGorevi(void *parametre) {
35  char satir[64];
36  for (;;) {
37    snprintf(satir, sizeof(satir), "Calisma suresi / Uptime: %lu s", (unsigned long)(millis() / 1000));
38    guvenliYaz(satir);
39    vTaskDelay(pdMS_TO_TICKS(2000));
40  }
41}
42
43void setup() {
44  Serial.begin(115200);
45  pinMode(LED_PIN, OUTPUT);
46  pinMode(BUTON_PIN, INPUT_PULLUP);
47  butonSemaforu = xSemaphoreCreateBinary();
48  seriKilit = xSemaphoreCreateMutex();
49  xTaskCreatePinnedToCore(butonGorevi, "Buton", 2048, NULL, 3, NULL, 1);
50  xTaskCreatePinnedToCore(raporGorevi, "Rapor", 2048, NULL, 1, NULL, 1);
51  attachInterrupt(digitalPinToInterrupt(BUTON_PIN), butonKesmesi, FALLING);
52}
53
54void loop() {
55  vTaskDelay(pdMS_TO_TICKS(1000));
56}
Inside an interrupt routine use only the FreeRTOS functions whose names end in FromISR (such as xSemaphoreGiveFromISR and xQueueSendFromISR). Calling Serial.print(), delay() or any function that waits inside an interrupt crashes the ESP32. Put IRAM_ATTR in front of the interrupt function; it places the function in fast RAM instead of flash. Once you take a mutex, always give it back on every path: if xSemaphoreGive() is forgotten in an error branch, every task waiting for that resource is locked forever.

Which core does Wi-Fi run on, and where should you put your tasks?

In the Arduino core the Wi-Fi driver, the TCP/IP stack and Bluetooth are pinned to core 0; loop() and Arduino events run on core 1. By default the ESP32's task watchdog also monitors the idle task on core 0 (IDLE0). If you put a task on core 0 that has priority and never waits, IDLE0 cannot run for 5 seconds, the Serial Monitor shows Task watchdog got triggered and the board restarts. The same task also delays the processing of network packets. A simple rule makes things easier:

JobSuggested coreWhy?
Fast, regular control, sensor sampling, motor control1Wi-Fi interruptions do not disturb the timing
Web server, MQTT, HTTP requests0 or 1, low priorityThe network stack is already on core 0; your task should wait often
Display updates, logging1, priority 1Not urgent, uses the spare time
Long calculations (FFT, encryption)1, or 0 at low priority, with vTaskDelay(1) in betweenSo the watchdog and other tasks are not starved

Stack size and watchdog errors

Every task has its own stack memory; local variables, function calls and library functions such as printf use this space. On the ESP32 stack size is given in bytes; the "word" unit mentioned in standard FreeRTOS documentation does not apply to the ESP32. 2048 bytes are enough for a simple LED task. Give tasks that use Serial.printf(), String operations and floating-point printing 3072–4096 bytes. Tasks that handle HTTPClient, TLS (HTTPS) or JSON may need 8192 bytes or more. If a stack overflows, the ESP32 reports Stack canary watchpoint triggered or A stack overflow in task ... has been detected and restarts. You can find out the minimum amount of a task's stack that has remained free so far with uxTaskGetStackHighWaterMark(); the value is in bytes, and if it drops below 500 bytes you should enlarge the stack. We explain how to read the error messages behind unexpected restarts in ESP32 Brownout and Guru Meditation.

Error messageMeaningFix
Task watchdog got triggered ... IDLE (CPU 0)A task on core 0 did not wait for 5 sAdd vTaskDelay(1) to the loop, lower the priority or move the task to core 1
Stack canary watchpoint triggered (task name)The named task's stack overflowedIncrease the stack value in xTaskCreatePinnedToCore
Guru Meditation Error: LoadProhibitedAn invalid address was readCheck whether the pointer passed to the task points to a local variable
Interrupt wdt timeout on CPU1An interrupt routine took too long or interrupts stayed disabledShorten the ISR and hand the work to a task with a semaphore
FreeRTOS Task "Gorev" should not return, Aborting now!The task function ended with returnUse an endless loop or call vTaskDelete(NULL) at the end

Project: LED, sensor and web server at the same time

Now let's combine what we have learned in one project. There will be three tasks: the sensor task reads the potentiometer every 200 ms and writes the average of the last 8 readings to a single-item queue; the LED task blinks the onboard LED at a speed set from the web page; and the web task shows the current sensor value on a page opened from your phone and offers links that change the LED speed. The tasks share data not through global variables but with xQueueOverwrite() and xQueuePeek(). loop() prints the free stack of each task and the free RAM every 10 seconds, so you can see during real operation whether the stacks are big enough. Replace the Wi-Fi network name and password with your own.

C++ (Arduino IDE)
1#include <WiFi.h>
2#include <WebServer.h>
3
4const char* WIFI_ADI   = "EvAgi_2G";       // Wi-Fi adı / network name
5const char* WIFI_SIFRE = "sifre1234";      // Wi-Fi şifresi / Wi-Fi password
6
7const int LED_PIN = 2;                     // dahili LED / onboard LED
8const int POT_PIN = 34;                    // ADC1, Wi-Fi ile çalışır / ADC1, works with Wi-Fi
9
10WebServer sunucu(80);
11QueueHandle_t sensorKutusu;                // tek öğe: son ortalama / one item: latest average
12QueueHandle_t hizKutusu;                   // tek öğe: LED yarım periyodu / one item: LED half period
13TaskHandle_t ledTutamac, sensorTutamac, webTutamac;
14
15void sensorGorevi(void *p) {
16  uint16_t son[8] = {0};
17  uint8_t sira = 0;
18  TickType_t sonUyanma = xTaskGetTickCount();
19  for (;;) {
20    son[sira] = analogRead(POT_PIN);
21    sira = (sira + 1) % 8;
22    uint32_t toplam = 0;
23    for (int i = 0; i < 8; i++) toplam += son[i];
24    uint16_t ortalama = toplam / 8;
25    xQueueOverwrite(sensorKutusu, &ortalama);       // eskisinin üzerine yaz / overwrite the old one
26    vTaskDelayUntil(&sonUyanma, pdMS_TO_TICKS(200));
27  }
28}
29
30void ledGorevi(void *p) {
31  pinMode(LED_PIN, OUTPUT);
32  uint32_t beklemeMs = 500;
33  for (;;) {
34    xQueuePeek(hizKutusu, &beklemeMs, 0);           // yeni hız varsa al / take a new speed if any
35    digitalWrite(LED_PIN, !digitalRead(LED_PIN));
36    vTaskDelay(pdMS_TO_TICKS(beklemeMs));
37  }
38}
39
40void anaSayfa() {
41  uint16_t deger = 0;
42  uint32_t hiz = 0;
43  xQueuePeek(sensorKutusu, &deger, 0);              // okur ama silmez / reads without removing
44  xQueuePeek(hizKutusu, &hiz, 0);
45  String html = "<!DOCTYPE html><html><head><meta charset='utf-8'>"
46                "<meta http-equiv='refresh' content='2'>"
47                "<meta name='viewport' content='width=device-width'></head><body>"
48                "<h2>ESP32 FreeRTOS</h2>";
49  html += "<p>Sensor: " + String(deger) + " / 4095</p>";
50  html += "<p>LED: " + String(hiz) + " ms</p>";
51  html += "<p><a href='/hiz?ms=100'>100 ms</a> | <a href='/hiz?ms=500'>500 ms</a> | "
52          "<a href='/hiz?ms=1000'>1000 ms</a></p></body></html>";
53  sunucu.send(200, "text/html", html);
54}
55
56void hizAyarla() {
57  uint32_t ms = sunucu.arg("ms").toInt();
58  if (ms >= 50 && ms <= 5000) {
59    xQueueOverwrite(hizKutusu, &ms);
60  }
61  sunucu.sendHeader("Location", "/");
62  sunucu.send(303);
63}
64
65void webGorevi(void *p) {
66  WiFi.mode(WIFI_STA);
67  WiFi.begin(WIFI_ADI, WIFI_SIFRE);
68  while (WiFi.status() != WL_CONNECTED) {
69    vTaskDelay(pdMS_TO_TICKS(500));                 // beklerken çekirdeği bırak / yield while waiting
70  }
71  Serial.print("Adres / Address: http://");
72  Serial.println(WiFi.localIP());
73  sunucu.on("/", anaSayfa);
74  sunucu.on("/hiz", hizAyarla);
75  sunucu.begin();
76  for (;;) {
77    sunucu.handleClient();
78    vTaskDelay(pdMS_TO_TICKS(2));                   // IDLE görevine nefes aldır / let the idle task run
79  }
80}
81
82void setup() {
83  Serial.begin(115200);
84  sensorKutusu = xQueueCreate(1, sizeof(uint16_t));
85  hizKutusu = xQueueCreate(1, sizeof(uint32_t));
86  uint32_t ilkHiz = 500;
87  xQueueOverwrite(hizKutusu, &ilkHiz);
88
89  xTaskCreatePinnedToCore(sensorGorevi, "Sensor", 2048, NULL, 2, &sensorTutamac, 1);
90  xTaskCreatePinnedToCore(ledGorevi, "LED", 2048, NULL, 1, &ledTutamac, 1);
91  xTaskCreatePinnedToCore(webGorevi, "Web", 6144, NULL, 1, &webTutamac, 0);
92}
93
94void loop() {
95  // boş yığın (bayt) ve boş RAM / free stack (bytes) and free heap
96  Serial.printf("Bos yigin / Free stack  Sensor: %u  LED: %u  Web: %u  |  Heap: %u\n",
97                (unsigned)uxTaskGetStackHighWaterMark(sensorTutamac),
98                (unsigned)uxTaskGetStackHighWaterMark(ledTutamac),
99                (unsigned)uxTaskGetStackHighWaterMark(webTutamac),
100                (unsigned)ESP.getFreeHeap());
101  vTaskDelay(pdMS_TO_TICKS(10000));
102}

After uploading, open the address shown in the Serial Monitor on your phone. The page refreshes every 2 seconds and the value changes as you turn the potentiometer. When you tap the links the LED speed changes instantly, but the sensor reading rhythm is never disturbed, because each job runs in its own task at its own pace. The web task sits on core 0 next to the network stack at low priority; because it waits 2 ms on every pass, the IDLE0 task can run and the watchdog is not triggered. The LED and sensor tasks are on core 1 and are not affected by Wi-Fi traffic. This structure is easy to extend: to update values instantly without reloading the page, add the WebSocket method from the ESP32 web server and WebSocket article, and to smooth noisy sensor values, replace the average in the sensor task with a median or exponential filter.

Comparison with the Raspberry Pi Pico: two cores in MicroPython

The RP2040 in the Raspberry Pi Pico is also dual-core, but there is no operating system: in MicroPython you start the second core with the _thread module, and only two threads run across the two cores. On the Arduino side, the arduino-pico core offers setup1() and loop1() functions for the second core. The MicroPython code below blinks the LED on the second core while reading the potentiometer on the first; the shared counter is protected with a lock, just like the mutex on the ESP32. There is more about the Pico's cores and PIO units in the Pico PIO and two cores article.

MicroPython
1import _thread, time
2from machine import Pin, ADC
3
4led = Pin(25, Pin.OUT)          # Pico dahili LED (Pico W'da Pin("LED")) / onboard LED (Pin("LED") on Pico W)
5pot = ADC(26)                   # GP26 = ADC0
6kilit = _thread.allocate_lock() # ortak veri kilidi / lock for shared data
7yanma_sayisi = 0
8
9def ikinci_cekirdek():
10    global yanma_sayisi
11    while True:
12        led.toggle()
13        with kilit:             # sayaç güvenle artar / counter updated safely
14            yanma_sayisi += 1
15        time.sleep_ms(300)
16
17_thread.start_new_thread(ikinci_cekirdek, ())   # çekirdek 1'de çalışır / runs on core 1
18
19while True:
20    deger = pot.read_u16()      # 0-65535
21    with kilit:
22        sayac = yanma_sayisi
23    print("Pot:", deger, "LED degisimi / toggles:", sayac)
24    time.sleep(1)

On the Pico this method works well for two jobs, but tools such as task counts, priorities, queues and the scheduler are not as rich as FreeRTOS on the ESP32. For projects with many concurrent jobs, network connections and precise timing, the ESP32 and FreeRTOS offer a more comfortable foundation. If you want to build Wi-Fi projects with the Pico, have a look at the Pico W Wi-Fi web server article.

Common mistakes and fixes

SymptomLikely causeFix
The board restarts as soon as a task is createdThe task function ends with return or the stack is too smallAdd an endless loop and raise the stack to 4096 bytes
loop() never runsA higher-priority task on core 1 never waitsAdd vTaskDelay() to that task or lower its priority to 1
Watchdog error when Wi-Fi is onA task on core 0 starves IDLE0Use vTaskDelay(1) in the loop or move the task to core 1
Values are occasionally nonsenseTwo tasks read and write the same global structure at onceMove the data with a queue or protect access with a mutex
Lines in the Serial Monitor get mixed upTwo tasks write to Serial at the same timeTake a mutex before writing and release it afterwards
The board crashes when the button is pressedSerial.print or a normal FreeRTOS function in the interrupt routineUse only FromISR functions in the ISR and hand the work to a task
analogRead() returns 4095 or 0 while Wi-Fi is onThe sensor is on an ADC2 pinUse one of the ADC1 pins GPIO 32–39
The code compiles on the ESP32-C3 but does not runCore 1 was requested on a single-core boardUse core 0 or tskNO_AFFINITY, or use xTaskCreate()
When moving to FreeRTOS, do not split everything into tasks at once. First move the most time-sensitive job in your working code, such as sensor sampling, into its own task and leave the rest in loop(). Check the stack with uxTaskGetStackHighWaterMark() after each new task. If you exchange all data between tasks through queues and access every shared piece of hardware through a mutex, you avoid most "sometimes it breaks" bugs from the start.

The ESP32's two cores and FreeRTOS turn complicated loop() functions full of millis() arithmetic into small, readable tasks that each focus on one job. Now that you know how to create tasks, set priorities, move data with queues, handle interrupts with semaphores and measure the stack, your Wi-Fi projects will run without stalling. If you are new to the ESP32, you will find the basics in What Is the ESP32?. In the BlueGrays app you can also explore ESP32 projects such as an async web server, WebSocket, an NTP clock, a temperature logger and smart lighting, each with step-by-step circuit diagrams and ready-to-use code.

Frequently asked questions

What is FreeRTOS on the ESP32?

FreeRTOS is a real-time operating system that runs inside the ESP32, and your Arduino code runs on top of it. It lets you split several jobs into separate tasks, give them priorities and spread them across the two cores. No separate installation is needed; functions such as xTaskCreate are ready to use in the ESP32 Arduino core.

Which core does loop() run on in the ESP32?

In the Arduino core, setup() and loop() run inside a task called loopTask on core 1 with priority 1. Wi-Fi, TCP/IP and Bluetooth are on core 0. You can see this yourself by printing xPortGetCoreID().

What is the difference between delay() and vTaskDelay() on the ESP32?

In the ESP32 Arduino core, delay() actually calls vTaskDelay(), so both release the core to other tasks while waiting. The busy waiting you know from the Arduino Uno happens on the ESP32 with delayMicroseconds() and empty while loops. For fixed-rate jobs vTaskDelayUntil() is more accurate.

How big should the xTaskCreatePinnedToCore stack size be?

On the ESP32 the stack size is in bytes. 2048 bytes is a good starting point for simple LED tasks, 3072–4096 for tasks using Serial.printf and String, and 8192 for heavy jobs such as HTTPS and JSON. Measure the real need with uxTaskGetStackHighWaterMark() and adjust.

How do I fix the ESP32 "Task watchdog got triggered" error?

This error means the idle task on core 0 could not run for 5 seconds; usually a task is looping without ever waiting. Add vTaskDelay(1) inside the loop, lower the task's priority or move it to core 1. Splitting long calculations into smaller chunks also helps.

How do I share data between tasks on the ESP32?

The safest way is FreeRTOS queues: data is sent with xQueueSend() and received with xQueueReceive(), and because it is copied, no half-read values occur. If only the latest value is needed, use a single-item queue with xQueueOverwrite() and xQueuePeek(). If you share hardware or a global structure, protect access with a mutex.

See all projects
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
26
ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)
ES-28Advanced
Premium

ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)

In this project, two buttons wired to the ESP32 (GPIO 5 counts up, GPIO 4 counts down) change a counter. The value updates instantly both on a 16x2 I2C LCD and, through the WebSocket support of ESPAsyncWebServer, in every connected browser without reloading the page. Instead of HTTP polling a single persistent connection is used, and the ESP32 sends the new value to everyone with ws.textAll().

4.5(14)
23
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
38
ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)
ES-13Intermediate
Premium

ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)

In this project, we control the brightness of an LED analogically using a potentiometer. The ESP32's ADC pin reads the 0-3.3V voltage from the potentiometer, and this value is then converted into a PWM (Pulse Width Modulation) signal and sent to the LED. As a result, as you turn the potentiometer, the LED gradually brightens and dims. With Arduino Core 3.0+, analogWrite() can be used directly; on the ESP32-S2/S3, the ADC resolution is fixed at 12-bit.

4.5(19)
32
ESP32 WS2812B NeoPixel Strip Control
ES-24Intermediate
Premium

ESP32 WS2812B NeoPixel Strip Control

WS2812B (NeoPixel) addressable LEDs are smart RGB LEDs that can be chained and controlled from a single data pin. In this project we drive an 8-LED WS2812B strip with the Adafruit_NeoPixel library and create a smooth rainbow animation. The ESP32's 3.3V logic works with most WS2812B batches; if it gets unstable, we show the fix with a 470Ω series resistor and a 1000µF capacitor. The animation shifts the hue in HSV color space.

4.9(19)
30
ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
ES-33Advanced
Premium

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)

The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.

4.3(10)
16
ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
ES-40Advanced
Premium

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)

Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

4.7(7)
12
ESP32 Smart Lighting (PIR + LDR + Relay + OLED)
ES-37Advanced
Premium

ESP32 Smart Lighting (PIR + LDR + Relay + OLED)

With an ESP32, a PIR motion sensor, an LDR light sensor and a relay module, we turn your hallway, bathroom or pantry into smart lighting. If the room is already bright, the light stays off even when there is motion, so it never wastes energy during the day. The light stays on for 30 seconds, and the time extends automatically while motion continues.

4.3(6)
11