🛠 Deux tâches FreeRTOS sur les deux cœurs
Objectives
Leverage the true strength of the ESP32: its dual Xtensa cores. You will create two FreeRTOS tasks, each pinned to a specific core, communicating via a queue. Typical use case: keep core 0 for the Wi-Fi/Bluetooth stack and core 1 for your application logic, just as the Arduino loop already does.
Hardware
- 1 ESP32 DevKit v1 board
- A PC with a serial port
- No soldering required
Full code
#include <WiFi.h>
QueueHandle_t file;
struct Mesure { float t; int rssi; };
void tacheReseau(void*) { // epinglee sur coeur 0, pres de la pile Wi-Fi
for (;;) {
Mesure m;
m.t = millis / 1000.0f;
m.rssi = WiFi.RSSI;
xQueueSend(file, &m, portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void tacheConsole(void*) { // epinglee sur coeur 1
Mesure m;
for (;;) {
if (xQueueReceive(file, &m, portMAX_DELAY)) {
Serial.printf("[coeur %d] t=%.0f s RSSI=%d\n",
xPortGetCoreID, m.t, m.rssi);
}
}
}
void setup {
Serial.begin(115200);
file = xQueueCreate(16, sizeof(Mesure));
WiFi.mode(WIFI_STA);
xTaskCreatePinnedToCore(tacheReseau, "reseau", 4096, NULL, 5, NULL, 0);
xTaskCreatePinnedToCore(tacheConsole, "console", 4096, NULL, 4, NULL, 1);
}
void loop { vTaskDelay(pdMS_TO_TICKS(1000)); }
Expected verification
The console displays a line every second: "[core 1] t=… s RSSI=…". The measurement is produced on core 0, consumed, and displayed on core 1. If you remove the pinning, the displayed core number changes depending on FreeRTOS scheduling.
Common errors
- Stack too small (4096 bytes here): a slightly heavy printf can crash the task (Guru Meditation); monitor uxTaskGetStackHighWaterMark.
- Two tasks writing to Serial simultaneously: interleaved output; centralize displays or protect with a mutex.
- Slow Wi-Fi calls made from loop: the radio stack runs on core 0, hence the benefit of task separation.
- delay works within a task (it yields control), but vTaskDelay(pdMS_TO_TICKS(…)) remains the explicit FreeRTOS syntax.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino