Embedded / IoT
Intermediate
ESP-IDF / Arduino ESP32 Core
ESP32 FreeRTOS 듀얼 코어 분산 태스크 및 스레드 세이프 큐(Queue) 통신ESP32 FreeRTOS Dual-Core Task Pinning and Thread-Safe Queue Communication
Core 0(Wi-Fi·센서 수집)과 Core 1(UI 렌더링·모터 제어)에 독립 태스크를 고정(PinToCore)하고 FreeRTOS Queue로 데이터를 안전하게 교환하는 멀티태스킹 패턴입니다.Pinning independent FreeRTOS tasks to Core 0 (Wi-Fi/sensor acquisition) and Core 1 (UI rendering/motor control) and exchanging data safely via FreeRTOS queues.
#Embedded #ESP32 #FreeRTOS #DualCore #Multithreading
핵심 개념ESP32(듀얼 코어 모델)는 2개의 Xtensa 32비트 LX6 코어(Core 0: PRO_CPU, Core 1: APP_CPU)를 탑재하고 있습니다. 단일
loop() 안에서 블로킹 네트워크 요청과 고속 센서 읽기, 디스플레이 갱신을 함께 수행하면 화면 끊김과 샘플링 지터가 발생하므로, xTaskCreatePinnedToCore로 역할을 분리하고 FreeRTOS Queue를 통해 값 복사(Copy-by-Value) 방식으로 데이터를 전달합니다.Key ConceptDual-core ESP32 chips feature two Xtensa 32-bit LX6 processors (Core 0:
PRO_CPU, Core 1: APP_CPU). Running blocking network requests, high-frequency sensor polling, and display refreshes inside a single loop() causes frame drops and timing jitter. Pinning dedicated tasks with xTaskCreatePinnedToCore and passing structs by value through a FreeRTOS Queue isolates workloads cleanly.1. FreeRTOS 듀얼코어 태스크 스케줄링 C++ 코드1. FreeRTOS Dual-Core Task Scheduling in C++
#include <Arduino.h>
struct SensorData {
int id;
float value;
};
QueueHandle_t dataQueue;
void SensorTask(void *pvParameters) {
SensorData data;
while (1) {
data.id = 1;
data.value = analogRead(34) * (3.3f / 4095.0f);
// 큐에 구조체 복사본 전송 (최대 대기시간 10ms)
xQueueSend(dataQueue, &data, pdMS_TO_TICKS(10));
vTaskDelay(pdMS_TO_TICKS(50)); // 20Hz 수집 주기 (워치독 양보 포함)
}
}
void DisplayTask(void *pvParameters) {
SensorData receivedData;
while (1) {
// 큐에 데이터가 들어올 때까지 블로킹 대기 (CPU 점유율 0%)
if (xQueueReceive(dataQueue, &receivedData, portMAX_DELAY) == pdPASS) {
Serial.printf("[Core %d] Sensor %d: %.2f V\n",
xPortGetCoreID(), receivedData.id, receivedData.value);
}
}
}
void setup() {
Serial.begin(115200);
dataQueue = xQueueCreate(10, sizeof(SensorData));
// Core 0에 센서 수집 태스크 고정
xTaskCreatePinnedToCore(SensorTask, "SensorTask", 4096, NULL, 1, NULL, 0);
// Core 1에 디스플레이/로직 태스크 고정
xTaskCreatePinnedToCore(DisplayTask, "DisplayTask", 4096, NULL, 1, NULL, 1);
}
void loop() {
vTaskDelete(NULL); // 불필요한 기본 Arduino loop 태스크 제거
}
#include <Arduino.h>
struct SensorData {
int id;
float value;
};
QueueHandle_t dataQueue;
void SensorTask(void *pvParameters) {
SensorData data;
while (1) {
data.id = 1;
data.value = analogRead(34) * (3.3f / 4095.0f);
// Copy struct into queue (up to 10ms timeout)
xQueueSend(dataQueue, &data, pdMS_TO_TICKS(10));
vTaskDelay(pdMS_TO_TICKS(50)); // 20Hz sampling interval (yields to watchdog)
}
}
void DisplayTask(void *pvParameters) {
SensorData receivedData;
while (1) {
// Block with 0% CPU usage until an item arrives in the queue
if (xQueueReceive(dataQueue, &receivedData, portMAX_DELAY) == pdPASS) {
Serial.printf("[Core %d] Sensor %d: %.2f V\n",
xPortGetCoreID(), receivedData.id, receivedData.value);
}
}
}
void setup() {
Serial.begin(115200);
dataQueue = xQueueCreate(10, sizeof(SensorData));
// Pin sensor acquisition task to Core 0
xTaskCreatePinnedToCore(SensorTask, "SensorTask", 4096, NULL, 1, NULL, 0);
// Pin display/logic task to Core 1
xTaskCreatePinnedToCore(DisplayTask, "DisplayTask", 4096, NULL, 1, NULL, 1);
}
void loop() {
vTaskDelete(NULL); // Delete unused default Arduino loop task
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- Core 0의 Wi-Fi/BT 프로토콜 스택 기아(Starvation) 주의: ESP-IDF와 아두이노 코어는 기본적으로 Core 0(
PRO_CPU)에서 Wi-Fi 및 Bluetooth 백그라운드 태스크와 인터럽트 워치독(TWDT)을 실행합니다. 따라서 Core 0에 배치한 사용자 태스크에는 반드시vTaskDelay()를 넣어 하위 우선순위 시스템 태스크와 IDLE 태스크에 실행 시간을 양보해야 워치독 리셋이 발생하지 않습니다. - FreeRTOS Queue의 값 복사(Copy-by-Value) 특성:
xQueueSend는 포인터가 가리키는 데이터를 큐 내부 버퍼로sizeof(SensorData)바이트만큼 직접 메모리 복사(memcpy)하므로,SensorTask의 지역 변수data가 다음 루프에서 덮어써져도 수신 측 데이터가 안전하게 보존됩니다. - 태스크 스택 워터마크 점검: 태스크 내부에서
printf나 무거운 문자열 포맷팅을 수행하면 2KB 미만의 작은 스택은 쉽게 오버플로우됩니다. 최소4096바이트 이상을 할당하고uxTaskGetStackHighWaterMark(NULL)로 여유 스택을 확인해야 합니다.
- Avoid Starving Core 0 System Tasks: ESP-IDF runs the Wi-Fi/Bluetooth protocol stack and Task Watchdog Timer (TWDT) on Core 0 (
PRO_CPU). Any user task pinned to Core 0 must yield periodically viavTaskDelay()or blocking queue calls so the IDLE task can reset the watchdog. - Copy-by-Value Semantics of FreeRTOS Queues:
xQueueSendcopiessizeof(SensorData)bytes directly into the queue's internal ring buffer, meaning local stack structs inSensorTaskcan be safely reused on the next iteration without race conditions. - Monitor Stack High-Water Marks: Functions like
Serial.printfrequire substantial stack space; allocate at least4096bytes per task and verify headroom during testing withuxTaskGetStackHighWaterMark(NULL).
네트워크·센서 I/O와 실시간 제어·렌더링 루프를 서로 다른 코어에 분리하고 FreeRTOS 큐로 연결하면, 데이터 경쟁(Race Condition) 없이 두 코어의 연산 자원을 고르게 활용할 수 있습니다.
Decoupling I/O acquisition on Core 0 from real-time rendering or control loops on Core 1 via FreeRTOS queues eliminates shared-memory race conditions and utilizes both CPU cores effectively.