FreeRTOS tasks and priorities
About this lesson
With FreeRTOS, each job in your firmware becomes a task: a C function with an endless loop, its own stack and a priority. On a single-core STM32F407VG, follow two tasks, sense (priority 2) and logger (priority 1), plus the idle task, millisecond by millisecond. You will see why the highest-priority Ready task always runs, how vTaskDelay frees the CPU, and how a waking task preempts a lower one. The OS course lessons on scheduling and real-time scheduling cover the general theory; here we use the FreeRTOS API.
A task is an endless loop
A FreeRTOS task is a C function with an endless loop. This one, sense, reads a sensor, then waits. It must never return. The kernel, the core of the RTOS, lets several such tasks take turns on one CPU.
task a C function that loops forever
void sense(void *p) { for (;;) { ... } }
kernel the core of the RTOS: it decides which task runs
rule a task function must never return
// STM32F4DISCOVERY, FreeRTOS. FreeRTOSConfig.h: configTICK_RATE_HZ 1000 (1 tick = 1 ms)
#include "FreeRTOS.h"
#include "task.h"
void readSensor(void); // about 0.5 ms of work (our example)
void writeLog(void); // about 6 ms of work (our example)
void sense(void *p) {
for (;;) {
readSensor();
vTaskDelay(5);
}
}
void logger(void *p) {
for (;;) {
writeLog();
vTaskDelay(20);
}
}
int main(void) {
// clock and pin setup omitted
xTaskCreate(sense, "sense", 256, NULL, 2, NULL);
xTaskCreate(logger, "logger", 256, NULL, 1, NULL);
vTaskStartScheduler(); // never returns while there is enough heap
for (;;) {}
}Read the lesson step by step
A task is an endless loop
A FreeRTOS task is a C function with an endless loop. This one, sense, reads a sensor, then waits. It must never return. The kernel, the core of the RTOS, lets several such tasks take turns on one CPU.
task a C function that loops forever void sense(void *p) { for (;;) { ... } } kernel the core of the RTOS: it decides which task runs rule a task function must never return // STM32F4DISCOVERY, FreeRTOS. FreeRTOSConfig.h: configTICK_RATE_HZ 1000 (1 tick = 1 ms) #include "FreeRTOS.h" #include "task.h" void readSensor(void); // about 0.5 ms of work (our example) void writeLog(void); // about 6 ms of work (our example) void sense(void *p) { for (;;) { readSensor(); vTaskDelay(5); } } void logger(void *p) { for (;;) { writeLog(); vTaskDelay(20); } } int main(void) { // clock and pin setup omitted xTaskCreate(sense, "sense", 256, NULL, 2, NULL); xTaskCreate(logger, "logger", 256, NULL, 1, NULL); vTaskStartScheduler(); // never returns while there is enough heap for (;;) {} }A stack and a priority each
xTaskCreate gives sense its own stack of 256 words (1,024 bytes on this 32-bit chip) and priority 2. A second task, logger, gets priority 1. A bigger number means more important. New tasks start Ready: able to run, waiting for the CPU.
xTaskCreate(sense, "sense", 256, NULL, 2, NULL); function sense name "sense" (for debugging) stack 256 words x 4 bytes = 1,024 bytes priority 2 (0 is the lowest) xTaskCreate(logger, "logger", 256, NULL, 1, NULL); both start in the Ready stateThe highest Ready task runs
vTaskStartScheduler() hands the CPU to the kernel. It adds an idle task at priority 0, then runs the highest-priority Ready task: sense, priority 2. This chip has one core, so exactly one task is Running at a time.
vTaskStartScheduler(); creates idle task, priority 0 Ready sense (2), logger (1), idle (0) picks the highest: sense (2) -> Running one core (Cortex-M4) -> one Running task t = 0 msvTaskDelay: wait without the CPU
sense reads its sensor in 0.5 ms, then calls vTaskDelay(5). It moves to Blocked until 5 ticks pass; our tick is 1 ms. A Blocked task uses no CPU time and cannot be picked to run.
t = 0 .. 0.5 ms sense runs readSensor() vTaskDelay(5) -> Blocked until tick 5 tick 1000 Hz -> 1 ms each (configTICK_RATE_HZ) Blocked uses no CPU timeNow the lower task runs
With sense blocked, the highest-priority Ready task is logger, priority 1, so it runs. It needs 6 ms of CPU to format and write a log line. logger never mentions sense: the kernel alone decides who runs.
Ready logger (1), idle (0) picks logger -> Running from 0.5 ms needs 6 ms of CPU for one pass by 5 ms 4.5 ms done, 1.5 ms leftPreemption at the 5 ms tick
At tick 5 sense's delay ends and it becomes Ready. 2 beats 1, so the kernel stops logger at once, mid-line, saves its registers on logger's own stack and runs sense. That is preemption.
tick 5 sense: Blocked -> Ready compare sense 2 > logger 1 switch logger -> Ready, registers saved on its stack sense -> Running preemption: a higher-priority task takes the CPU at onceBack where it stopped
sense blocks again after 0.5 ms, until tick 10. logger resumes exactly where it stopped, from its saved registers. It finishes at 7 ms and calls vTaskDelay(20), so it is Blocked until tick 27.
t = 5 .. 5.5 sense runs, then Blocked until tick 10 t = 5.5 .. 7 logger resumes from its stack, finishes vTaskDelay(20) -> logger Blocked until tick 27Nothing Ready: the idle task
From 7 ms none of our tasks is Ready, so the idle task runs. It can put the CPU into a low-power mode. At tick 10 sense wakes and preempts idle, exactly as it preempted logger.
t = 7 .. 10 idle runs (priority 0) tick 10 sense wakes, preempts idle t = 10 .. 10.5 sense, then idle again idle hook a common place to enter a low-power modeA task that never blocks
Delete vTaskDelay(5) and sense is always Ready. Priority 2 always wins, so logger and idle never run again: they starve. With priorities, high-priority tasks must block to wait for time or an event.
what if line 4 is deleted? sense always Ready -> always Running logger never runs (starved) idle never runs (starved) rule: high-priority tasks must block
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Three tasks are Ready, with priorities 0, 1 and 3. Nothing else can run. Which one does FreeRTOS put in the Running state on a single-core chip?
The task placed in the Running state is always the highest-priority task that is able to run. Larger numbers mean higher priority; 0 is the idle task's level.
02On this 32-bit Cortex-M4, xTaskCreate(sense, "sense", 256, NULL, 2, NULL) gives the task a stack of how many bytes?
The stack size is given in words, not bytes. One stack word is 4 bytes on this port, so 256 x 4 = 1,024 bytes.
03logger (priority 1) is running when sense's vTaskDelay ends at tick 5. What happens?
FreeRTOS is preemptive by default: as soon as a higher-priority task becomes Ready, it takes the CPU. logger goes back to Ready and later resumes exactly where it stopped.
04What does a task do while it is in the Blocked state, for example inside vTaskDelay?
Blocked tasks wait for time or an event. They use no processing time, which is what lets lower-priority tasks and the idle task run.
05A priority 3 task polls a flag in a loop and never calls vTaskDelay or any other blocking function. What is the effect on priority 1 and 2 tasks?
A high-priority task that never enters the Blocked or Suspended state starves every lower-priority task. It should block to wait for the event instead of polling.
Glossary
- Task
- In FreeRTOS, a C function with an endless loop that the kernel runs as an independent job, with its own stack and priority.
- Kernel
- The core of a real-time operating system (RTOS): it decides which task runs and switches between them.
- Priority
- A number from 0 to configMAX_PRIORITIES - 1 given to each task. Higher numbers are more important; the idle task uses 0.
- Ready state
- Able to run, but waiting because a task of equal or higher priority has the CPU.
- Blocked state
- Waiting for time to pass or for an event. A Blocked task uses no CPU time.
- Preemption
- The kernel stopping a running task at once because a higher-priority task has become Ready.
- Tick
- The periodic interrupt FreeRTOS uses to measure time. configTICK_RATE_HZ sets how many there are per second.
- Idle task
- A priority 0 task the scheduler creates itself. It runs when no other task is Ready.
Notes and sources
- The card shows only the sense task and its creation. The whole program also defines logger the same way with priority 1, and main() creates both tasks and calls vTaskStartScheduler(). readSensor() and writeLog() stand for real work; 0.5 ms and 6 ms are example times we chose.
- vTaskDelay counts ticks, not milliseconds. We set configTICK_RATE_HZ to 1000, so one tick is 1 ms and vTaskDelay(5) waits 5 ms. Portable code writes vTaskDelay(pdMS_TO_TICKS(5)). The delay counts from the tick when it is called, so the period drifts; vTaskDelayUntil keeps an exact period.
- A real context switch takes a few microseconds, and the tick interrupt itself uses a little CPU time. The timeline ignores both.
- Tasks may share a priority. Then, by default, Ready tasks of equal priority take turns, switching at each tick: round-robin time slicing. The next lesson shows how the tick picks a task.
- This board's STM32F407VG has one Cortex-M4 core. On a dual-core chip such as the ESP32, FreeRTOS can run two tasks at once, one per core, so a lower-priority task may run beside a higher one.
- FreeRTOS: Task states
- FreeRTOS: Task priorities
- FreeRTOS: Scheduling (single-core, AMP and SMP)
- FreeRTOS: Implementing a task
- FreeRTOS: xTaskCreate
- FreeRTOS: vTaskDelay
- FreeRTOS: vTaskStartScheduler
- FreeRTOS: The idle task
- FreeRTOS: Customisation (FreeRTOSConfig.h)
- FreeRTOS-Kernel: ARM_CM4F port, portmacro.h
- STM32F4DISCOVERY board (STM32F407VG) hardware summary
- ESP-IDF: FreeRTOS (IDF), symmetric multiprocessing on the dual-core ESP32
- Valvano, Real-Time Operating Systems for ARM Cortex-M Microcontrollers (contents)
- Lee & Seshia, Introduction to Embedded Systems (UC Berkeley EECS 149)
Quiz Unlocks after the last step.