READYCPU · Cortex-M4Running: one task at a timeBLOCKED1void sense(void *p) {2 for (;;) {3 readSensor();4 vTaskDelay(5);5 }6}7xTaskCreate(sense, "sense", 256,8 NULL, 2, NULL);sense · p2logger · p1idle · p0tick count0sense2logger1idle0
Who has the CPU sense · 2logger · 1idle · 0 024681012 time (ms) what if line 4 were deleted?never runs: starvednever runs: starved t
Back: Ready tray, the one CPU core, Blocked trayFront: the sense task's code, each task's stack, the tick countTokens: the three tasks (name and priority); below, a timeline of who had the CPUFreeRTOS on one Cortex-M4 core: tasks wait in Ready, run one at a time on the CPU, or wait without the CPU in Blocked. sense (priority 2) runs first and blocks with vTaskDelay(5); logger (priority 1) runs until sense wakes at 5 ms and preempts it; logger resumes and blocks at 7 ms; then the idle task (priority 0) runs. A high-priority task that never blocks would starve all the others.

What a task is

  1. 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.

Who gets the CPU

The rule

What happens

;; step 1/9 · task
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 (;;) {}
}

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.