When your device needs to do several things at once — read sensors, update a display, communicate over WiFi, respond to button presses — a simple loop is not enough. An RTOS manages this for you.
The problem with a simple loop
while (1) {
read_sensors(); // 10ms
update_display(); // 50ms
send_wifi_data(); // 100ms
check_buttons(); // 1ms
}
The loop takes 161ms to complete one cycle. Button presses that happen during send_wifi_data() might be missed. The display updates feel sluggish.
What an RTOS adds
An RTOS adds task scheduling. Each function becomes a task with its own stack and priority. The scheduler decides which task runs and when, switching between them so fast it appears they run simultaneously.
FreeRTOS: the standard
FreeRTOS is the most widely used RTOS for microcontrollers. It is free, well-documented, and supported on almost every platform including STM32 and ESP32.
void sensor_task(void *pvParameters) {
while (1) {
read_sensors();
vTaskDelay(pdMS_TO_TICKS(10)); // Yield for 10ms
}
}
void wifi_task(void *pvParameters) {
while (1) {
send_wifi_data();
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
int main(void) {
xTaskCreate(sensor_task, "Sensor", 256, NULL, 2, NULL);
xTaskCreate(wifi_task, "WiFi", 512, NULL, 1, NULL);
vTaskStartScheduler();
}
Key RTOS concepts
Tasks: Independent threads of execution, each with its own stack.
Priorities: Higher-priority tasks preempt lower-priority ones. The sensor task above has priority 2 and will interrupt the WiFi task if both are ready to run.
Queues: Safe way to pass data between tasks. A sensor task can put readings into a queue that a display task reads from.
Semaphores and mutexes: Prevent two tasks from accessing shared resources simultaneously.
When do you need an RTOS?
When you have strict timing requirements, multiple concurrent operations, or need clear separation between different parts of your firmware. For simple applications with one thing to do, bare metal is simpler and more predictable.



