Why Use FreeRTOS on STM32?
FreeRTOS is the most widely deployed real-time operating system, running on billions of devices. When your STM32 project needs to handle multiple tasks concurrently — such as reading sensors, updating a display, handling communication, and responding to user input — FreeRTOS provides a structured, efficient framework.
Key FreeRTOS Concepts
Tasks
Tasks are independent threads of execution. Each task has its own stack and priority. FreeRTOS uses a preemptive priority-based scheduler.
xTaskCreate(vSensorTask,"SensorTask",256,NULL,2,&xSensorHandle);
Queues
Queues provide thread-safe data passing between tasks and ISRs with blocking read/write operations.
Semaphores and Mutexes
- Binary Semaphore — Task synchronization (ISR to task notification)
- Mutex — Mutual exclusion with priority inheritance
Setting Up FreeRTOS with STM32CubeMX
- In STM32CubeMX, go to Middleware → FREERTOS
- Select Interface: CMSIS_V1
- Set USE_PREEMPTION = Enabled, TICK_RATE_HZ = 1000
- Define tasks, queues, and semaphores in the GUI
- Generate code — CubeMX creates the task scaffolding automatically
Practical Example: Sensor Logger System
- Sensor Task (Priority 2) — Reads temperature/humidity via I2C every 100ms, sends to queue
- Display Task (Priority 1) — Reads from queue, updates LCD every 500ms
- Communication Task (Priority 3) — Sends data to cloud via UART/WiFi module
void vSensorTask(void *pvParameters) {
for (;;) {
float temp = read_temperature();
xQueueSend(sensorQueue, &temp, pdMS_TO_TICKS(100));
vTaskDelay(pdMS_TO_TICKS(100));
}
}
Memory Management
FreeRTOS offers 5 memory allocation schemes. heap_4 coalesces adjacent free blocks and is recommended for most projects.
Debugging FreeRTOS Applications
- Use FreeRTOS+Trace or Percepio Tracealyzer for visualization
- Enable
configCHECK_FOR_STACK_OVERFLOW = 2for runtime stack checking - Use
configASSERT()to catch stack overflows and NULL pointers
On STM32F4 (168 MHz Cortex-M4F), task context switch takes approximately 12 clock cycles. FreeRTOS uses only 3-9 KB of RAM for kernel data structures.
Need professional FreeRTOS development? InnovChip’s team has delivered 200+ FreeRTOS-based products for industrial, medical, and consumer applications.
