Embedded RTOS

A stop task must finish within 10 ms of a press. It shares an SPI bus with a slow logger. With a plain semaphore as the lock, a 15 ms radio burst gets in between, and the stop task finishes 18 ms after the press. A mutex that lends the logger the stop task's priority finishes it in 3 ms, at any burst length.

Pick a design, then drag the radio burst longer. Watch where the stop task finishes against the 10 ms line. Then we build, piece by piece, tasks, the tick and the switch, queues, locks, inheritance, interrupts, memory and the two common kernels.

You need Lesson 6's interrupts and deadlines and a little C. We build the rest from zero.

Lesson 7 of the Embedded Systems series, the last. Before: Lesson 6, Real-Time Systems. Deadlines and response-time analysis: The Real-Time Mental Model. The same kernel from the inside: RTOS Internals. The hands-on track is Firmware from Zero.

Press stop during a log write

15 ms

Illustrative toy, simulated in 10 µs steps with no switch cost. The logger holds the SPI lock from 0 to 4 ms. The press comes at 2 ms. The stop task needs 0.3 ms, then the bus for 0.5 ms, then 0.2 ms. The radio starts at 3 ms.

Chapter 0

One Loop Cannot Wait for Two Things

Grow Lesson 1's node until its superloop breaks, then give each job its own task

Lesson 1 built a node as a superloop: sensors 2 ms, filtering 3 ms, display 12 ms, buttons 0.1 ms, serial 3 ms. One pass takes 20.1 ms. The button got an interrupt, so the motor still stops at once.

Now the product grows. The sensor and the filter feed a control loop that must run every 10 ms. A radio sends a report, then waits up to 200 ms for an acknowledgement (ACK), the reply that says it arrived. In a superloop, waiting means spinning in a loop that checks a flag. So one pass now takes 220.1 ms, and the control code runs once in each.

One loop, or one task per job

Yellow ticks mark where the control code should run, every 10 ms. Warm blocks are code that runs. Hatched is the radio spinning on its ACK, and faded is a task that sleeps. Switch the design, then turn on the ACK wait.

Illustrative: Lesson 1's toy task times. RTOS view: control 5 ms every 10 ms at the top priority, serial 3 ms every 20 ms, display 12 ms once per 100 ms. The radio sleeps until its ACK.

A real-time operating system (RTOS) splits the work into tasks. Each task is a loop with its own priority. A task that waits for something blocks: it uses no CPU until the event comes. The kernel's scheduler always runs the most urgent task that is ready.

In the RTOS view, control starts at 0, 10, 20 and so on to 90 ms, every time. The display takes 12 ms of work but finishes at 38 ms, because it steps aside for control and serial. The work needs 77% of the core: 0.50 + 0.15 + 0.12.

The price is real. Each task needs its own stack in RAM. Each switch between tasks costs a few microseconds. Two tasks can now touch the same data at the same time. And a lock can make the most urgent task wait for the least urgent, which is the hero's story. A miss means different things in different systems: hard, firm and soft.

Symptom: after the radio arrives, the control loop runs slow and the display freezes during every report.

Measure: set a spare pin high at the start of the control code. On a scope its period is 20.1 ms, or 220 ms during a report, not 10 ms.

Fix: give each job a task with a priority, and let the radio block on its ACK instead of spinning.

The road

  1. Tasks: a loop with a stack, a state and a priority, and how it waits.
  2. The switch: the tick picks, PendSV swaps 16 words.
  3. Queues: copy data from one task to another, and size the queue.
  4. Locks: a race, and which lock to use: semaphore or mutex.
  5. Inversion: the hero's bug, Mars Pathfinder, and inheritance.
  6. ISR to task: keep the handler short, wake a task.
  7. Memory: RAM per task, and catching a stack overflow.
  8. Two kernels: FreeRTOS and Zephyr side by side.
  9. Showcase: run the node, plant faults.
  10. Field guide: the numbers, the bugs, the series in one page, and when to skip the RTOS.
The superloop's radio spins for up to 200 ms waiting for an ACK. How often does the control code run?

Chapter 1

A Task Is a Loop That Can Block

Create a task, follow its four states, and make it run on time

A task is a C function that never returns. It has its own stack, the memory that holds its local variables and return addresses, and its own priority. The kernel keeps a task control block (TCB) for each task: its saved stack pointer, its priority, its state and its name. In FreeRTOS a higher number is more urgent, and the idle task sits at priority 0.

c
void vControl(void *arg) {
    TickType_t last = xTaskGetTickCount();
    for (;;) {
        read_sensor_and_filter();                       // 3 ms of work
        xTaskDelayUntil(&last, pdMS_TO_TICKS(10));   // wake at last + 10 ms
    }
}
xTaskCreate(vControl, "ctl", 256, NULL, 3, NULL);  // 256 words = 1,024 B of stack

A task is always in one of four states. Running: it has the core, and one core has one Running task. Ready: it could run, but a more urgent task has the core. Blocked: it waits for time or an event, with a timeout, and uses no CPU. Suspended: someone called vTaskSuspend(), and only vTaskResume() brings it back.

How does a task wait 10 ms? vTaskDelay(N) blocks for N ticks counted from the call. Call the run time of one pass C, the delay in ticks N, and the tick period ttick. The task's real period is T:

Say it aloud

T is about C plus N times t-tick.

T
T the time from one start of the task's work to the next, in ms.
C
C the time the work takes before the task calls vTaskDelay(), preemptions included.
N
N the number of ticks passed to vTaskDelay().
ttick
t-tick the tick period: 1 ms at a 1,000 Hz tick. The task wakes on a tick, so T is right to within one tick.
In plain words

The delay starts only when the work ends. So the period is the work time C plus the N ticks of delay. If C changes from pass to pass, so does T.

With numbers

With made-up numbers: C = 3 ms, N = 10, t-tick = 1 ms. T = 3 + 10 × 1 = 13 ms, so the loop runs 76.9 times a second, not 100. In a minute that is 4,615 runs instead of 6,000.

Delay from now, or delay until

Each row is a separate run of the same task. Solid warm means Running, an outline means Ready, and faded means Blocked. Yellow ticks mark every 10 ms. Drag the work time, then add a more urgent task.

3.0 ms

Illustrative: a 1 ms tick, both runs released at 0. A delay wakes the task at the N-th tick after the call, as the FreeRTOS kernel counts it.

xTaskDelayUntil(&last, N) wakes the task at an absolute tick, last + N, and then moves last on by N. The work time no longer adds to the period, so the loop runs at exactly 10 ms while C stays under 10 ms. vTaskDelayUntil() is its older name.

Symptom: a control loop runs slow by a fixed share, and gets slower each time someone adds code to it.

Measure: toggle a pin at the top of the loop. A 13 ms period from a 10-tick delay names vTaskDelay().

Fix: use xTaskDelayUntil() with a last variable set once before the loop.

A task does 4 ms of work, then calls vTaskDelay(pdMS_TO_TICKS(20)) at a 1 kHz tick. About how many times a second does it run?

Chapter 2

The Tick Picks, PendSV Swaps

Step through one context switch on a Cortex-M3, word by word, and price the kernel's time

The kernel keeps time with a timer interrupt, the tick: on a Cortex-M, usually SysTick at configTICK_RATE_HZ. We use 1,000 Hz; the FreeRTOS Kernel Book calls 100 Hz typical. Each tick moves any task whose delay ran out to Ready. If it beats the running task, a switch is due.

The tick handler does not swap tasks itself. It pends PendSV, an exception the kernel sets to the lowest priority, so the swap runs after every other handler and never delays one. In the FreeRTOS Cortex-M3 port, tasks run on the process stack pointer (PSP) and handlers on the main stack pointer (MSP).

Park one task, wake another

Left: the running logger's stack. Right: the parked stop task's. Purple cells hold saved words. Press Next step; turn on a busy UART handler to see PendSV wait.

Real word counts: the Cortex-M3 stacks 8 words on entry, and the FreeRTOS ARM_CM3 port's PendSV saves r4 to r11. Cycle counts are illustrative.

The hardware pushes 8 words (r0 to r3, r12, LR, PC, xPSR) onto the task's stack. PendSV pushes r4 to r11 and writes the stack pointer into the TCB. That is 16 words, 64 bytes, per parked task. Only the PSP changes.

Call the tick rate ftick and the cycles of one tick handler ctick. Call the switches per second fsw, the cycles of one switch csw, and the core clock f. The kernel's share of the core is Uos:

Say it aloud

U-os equals f-tick times c-tick, plus f-switch times c-switch, all over f.

Uos
U-os the share of the core the kernel spends on ticks and switches, from 0 to 1.
ftick
f-tick ticks per second: configTICK_RATE_HZ.
ctick
c-tick cycles for one tick handler that wakes nobody.
fsw
f-switch context switches per second.
csw
c-switch cycles for one whole switch.
f
f the core clock: 72 MHz on the STM32F103.
In plain words

Multiply the tick rate f-tick by c-tick, add f-switch times c-switch, and divide by the clock f. That share never reaches your tasks.

With numbers

With made-up costs, 100 cycles per tick and 200 per switch, and 2,000 switches a second: at 1 kHz, U-os = (100,000 + 400,000) / 72,000,000 = 0.69%. At a 10 kHz tick it is 1.94%, for delays ten times finer.

Measure your c-switch with a pin or the cycle counter (Lesson 6) around PendSV. Equal priorities share the core one tick at a time: time slicing. vTaskGetRunTimeStatistics() reports each task's share.

Symptom: a 5 ms delay never waits, and the task hogs the core.

Measure: print pdMS_TO_TICKS(5). At a 100 Hz tick it is 5 × 100 / 1,000 = 0.5, which integer division makes 0 ticks.

Fix: pick a tick rate that resolves your shortest delay, or wait on an event or a hardware timer instead.

The tick handler finds a more urgent task ready. What does it do?

Chapter 3

A Queue Copies the Data and Wakes the Reader

Pass ADC samples from an interrupt to a task, and size the queue for the longest stall

The ADC finishes a sample every 1 ms. Its interrupt must hand the sample to the filter task without a shared variable that both sides write. A queue does this. It is a first-in, first-out list of fixed-size slots. The sender copies an item in; the reader copies it out. FreeRTOS queues items by copy, not by reference, so the sender may reuse its variable at once.

c
QueueHandle_t q = xQueueCreate(8, sizeof(uint16_t));     // 8 slots of 2 bytes

void ADC1_2_IRQHandler(void) {
    uint16_t s = ADC1->DR;  BaseType_t woken = pdFALSE;
    if (xQueueSendFromISR(q, &s, &woken) != pdPASS) dropped++;   // full: never blocks
    portYIELD_FROM_ISR(woken);                                        // Chapter 6
}
void vFilter(void *arg) {
    uint16_t s;
    for (;;) if (xQueueReceive(q, &s, portMAX_DELAY)) filter(s);   // blocks while empty
}

A task that reads an empty queue blocks, and the kernel wakes the most urgent waiting reader when an item lands. A task that sends to a full queue can block too, with a timeout. An interrupt cannot block, so xQueueSendFromISR() returns errQUEUE_FULL and the sample is lost.

Stall the reader, watch the slots

Blue ticks are samples, one per ms. Purple bars are full slots. The warm lane is the filter task; the gap is a stall, while more urgent tasks run. Red crosses are lost samples. Drag the stall and the queue length.

7.5 ms
5 slots

Illustrative: the stall starts just before a sample (the worst phase), and ten stalls come in each second. The reader drains the queue at once when it returns.

How many slots? Call the time between samples Tp and the longest stretch the reader can be away W. Every sample in that stretch must fit. The queue needs N slots:

Say it aloud

N is at least the ceiling of W over T-p.

N
N the queue length: how many items it holds.
⌈ ⌉
the ceiling of round up to a whole number, because a part of a sample still takes a slot.
W
W the longest time the reader cannot run: more urgent tasks, a lock it waits for.
Tp
T-p the time between two items from the producer: 1 ms here.
In plain words

Divide the reader's longest absence W by the producer's period T-p. Round up. That many items arrive with nobody to take them, so N must hold them all.

With numbers

With made-up numbers: T-p = 1 ms and W = 7.5 ms. N ≥ ⌈7.5⌉ = 8 slots, 16 bytes of 2-byte samples. A queue of 5 keeps 5 and loses 3 in each stall: 30 a second at ten stalls.

Symptom: gaps in the sensor data, only while the radio sends.

Measure: count the errQUEUE_FULL returns in the handler, and log the most items the queue ever held (uxQueueMessagesWaiting()).

Fix: size N from the worst W, or raise the reader's priority so W shrinks.

Samples arrive every 0.5 ms. The reader can be away for 6.2 ms. What is the shortest queue that loses nothing?

Chapter 4

Signal With a Semaphore, Guard With a Mutex

Lose updates in a race, then pick the lock that fits each job

Two tasks add to one counter. In C it is count++. On the Cortex-M3 it is three instructions: load the value into a register, add one, store it back. If a more urgent task runs between the load and the store, it adds its own one and stores. Then the first task stores its stale value on top, and one update is gone. This is a race.

Preempt a read-modify-write

The bar is one pass of the low task's loop, 8 cycles. Purple marks the 3 cycles after the load and before the store. Each bar counts the urgent task's preemptions that land on that cycle; each one adds 1. Run 1,000, then lock the update.

Illustrative cycle counts. Each run draws preemption times from a seeded generator; the first run uses seed 1.

How many updates go? Call the preemptions n, the cycles of one loop pass k, and the cycles between the load and the store w. The expected loss is L:

Say it aloud

L is about n times w over k.

L
L the expected number of lost updates.
n
n how many times the urgent task preempts and adds one.
w
w the cycles in the window from the load to the store.
k
k the cycles of one pass of the low task's loop. A preemption is equally likely at any of them.
In plain words

The window is w cycles out of every k, so a share w over k of the preemptions land inside it. Each of those loses one update. Multiply by n.

With numbers

With made-up cycles: n = 1,000, w = 3, k = 8. L ≈ 1,000 × 3 / 8 = 375 lost updates. The first seeded run loses 385. A test that preempts ten times may lose none, which is why races pass the bench.

The fix is to make the three instructions one step that no task can split. For a section this short, a critical section is cheapest: taskENTER_CRITICAL() raises BASEPRI to the kernel's limit on the Cortex-M3, so no task switch and no kernel-aware interrupt can enter. For longer work, take a lock. Which lock?

ObjectJobOwner?From an ISR?
Binary semaphoresignal: one side gives, the other takes and wakesnogive, yes
Counting semaphorecount events, or a pool of N buffersnogive, yes
Mutexguard shared data or a busyes, with priority inheritanceno
Recursive mutexa mutex the owner may take againyesno

Symptom: two tasks stop for good, and the CPU sits in the idle task.

Measure: halt in the debugger. Each task waits on a mutex that the other holds: a deadlock.

Fix: take locks in one global order everywhere, and give each take a timeout a little longer than the longest hold, as the Kernel Book advises.

The button ISR must wake the stop task. Which object fits?

Chapter 5

Priority Inversion, and the Mutex That Lends Its Priority

Follow the bug that reset a spacecraft, then bound how long a lock can hold your most urgent task

After Mars Pathfinder landed in July 1997, its computer began to reset itself. Glenn Reeves, its flight software lead, gave the cause in a December 1997 email. A high-priority task, bc_dist, had to finish within each cycle of an 8 Hz bus. A low-priority weather task, ASI/MET, held a mutex inside the VxWorks select() code, and medium-priority tasks kept preempting it. bc_dist blocked on that mutex, missed its cycle, and the bus scheduler reset the computer.

This is priority inversion: the most urgent task waits for the least urgent while every task in between runs. The team reproduced it on a ground copy within 18 hours. The mutex's inheritance option was off; a patch changed one global variable to turn it on.

With priority inheritance, a mutex holder runs at the priority of its most urgent waiter until it gives the mutex back. Under the priority ceiling protocol, each lock's ceiling is the priority of its most urgent user, and a task may lock only if it beats every ceiling held by others.

Chain the blocking

H needs S1, then S2. L1 takes S1 at 0 ms, L2 takes S2 at 1 ms. Purple bars mark a held lock; dashed purple is H waiting.

Illustrative tasks in 10 µs steps: H needs 1.5 ms; each low task holds its lock 3 ms. Protocols per Sha et al. (1990).

Sha, Rajkumar and Lehoczky proved the bounds in 1990. Call n the lower tasks that can block H, m the locks that can block it, and zmax the longest critical section among them. Under inheritance, the blocking B is:

Say it aloud

B is at most the min of n and m, times z-max.

B
B the longest H can wait on lower tasks for locks, in ms.
min
the min of the smaller count: each low task, and each lock, can block H once.
n
n lower tasks sharing a lock with H.
m
m the locks that can block H.
zmax
z-max the longest of their critical sections. The ceiling protocol allows one.
In plain words

Take the smaller of n and m. H waits through at most that many sections, each no longer than z-max.

With numbers

In the device: n = 2, m = 2, z-max = 3 ms. Inheritance allows B ≤ 6 ms; the run shows 4.0 ms. The ceiling allows 3 ms; the run shows 1.0 ms.

Add B to the response-time test in The Real-Time Mental Model. FreeRTOS and Zephyr mutexes use inheritance, not the ceiling; a FreeRTOS task keeps its borrowed priority until it releases every mutex. Inheritance bounds inversion but does not fix it (Kernel Book), so keep sections short, or let one gatekeeper task own the bus.

Symptom: an urgent task misses, or a check resets the chip, now and then under heavy load.

Measure: trace lock holds. A miss while a low task holds the lock and medium tasks run is inversion.

Fix: guard shared resources with a mutex, never a binary semaphore.

In the hero with a semaphore, the stop task waits 3 ms plus the radio burst. What changes with a mutex?

Chapter 6

Keep the Handler Short, Let a Task Do the Work

Wake a task from an interrupt, and see what one forgotten line costs

The stop button's handler still cuts the motor at once, as in Lesson 1. The rest takes milliseconds: ramp the drive down over SPI, log the event, tell the radio. In the handler, that work would hold off every less urgent interrupt. So the handler gives a semaphore, and a task does the work. Engineers call this deferred interrupt processing.

c
void EXTI0_IRQHandler(void) {
    EXTI->PR = 1u;  motor_off();                 // the urgent part, now
    BaseType_t woken = pdFALSE;
    xSemaphoreGiveFromISR(stopSem, &woken);       // sets woken if a more urgent task is now Ready
    portYIELD_FROM_ISR(woken);                    // switch on exit; forget it and wait for the tick
}

An interrupt may call only the FromISR functions, which never block. If the give wakes a task more urgent than the one interrupted, it sets woken, and portYIELD_FROM_ISR(woken) makes the handler return straight into that task. Without it, the Kernel Book says, the task waits for the scheduler to run, at worst until the next tick.

Call the handler's run time tISR, one switch tsw, the tick period Ttick, and y 1 if the handler yields, 0 if not. The worst wait from the press to the task's first line is L:

Say it aloud

L is at most t-ISR plus t-switch plus, one minus y, times T-tick.

L
L the deferred latency: press to the task's first line, in µs.
tISR
t-ISR the handler's run time, entry included.
tsw
t-switch one context switch.
y
y 1 if the handler calls portYIELD_FROM_ISR with woken set, 0 if it does not.
Ttick
T-tick the tick period, the longest wait for the scheduler to run on its own.
In plain words

Add the handler time t-ISR and one switch t-switch. If the handler does not yield, y is 0, so add up to a whole tick T-tick while the task sits Ready.

With numbers

With made-up costs: t-ISR = 2 µs, t-switch = 200 cycles at 72 MHz = 2.78 µs, T-tick = 1,000 µs. Yielding, L = 4.78 µs every time. Not yielding, L can reach 1,004.78 µs; over 10,000 seeded presses the mean is 504.6 µs.

Press 10,000 times

Each bar counts presses by the wait from the press (pink) to the stop task's first line. Turn the yield off and on, then move the button's interrupt above the kernel's limit.

Illustrative costs, 10,000 presses spread evenly over a 1 ms tick with a seeded generator (seed 3). The kernel limit is configMAX_SYSCALL_INTERRUPT_PRIORITY = 5, in the STM32F103's 4 priority bits.

On a Cortex-M, a handler that calls the kernel must sit at configMAX_SYSCALL_INTERRUPT_PRIORITY or a less urgent (numerically higher) level. The port warns that the default, 0, is always invalid. The kernel never delays a handler above the limit, so Lesson 6's 20 kHz current loop goes there and calls no kernel function.

A task notification (vTaskNotifyGiveFromISR()) is a faster, smaller semaphore for a single receiving task. In Zephyr, k_sem_give() is safe in an interrupt, and k_work_submit() hands a function to the system workqueue thread.

Symptom: the stop task starts 0.5 ms late on average, and up to 1 ms.

Measure: toggle one pin in the handler and another at the task's first line. A delay spread evenly from 0 to 1 tick names a missing yield.

Fix: pass woken to every FromISR call and end the handler with portYIELD_FROM_ISR(woken).

A handler gives a semaphore that wakes a task, but never calls portYIELD_FROM_ISR. The tick is 1 kHz. When does the task run?

Chapter 7

Every Task Owns a Stack

Add up the RAM of five tasks, then find out which check catches an overflow

The STM32F103C8 has 20 KB of SRAM (Lesson 2 maps it), and every task takes a stack and a TCB from it. xTaskCreate() takes them from the FreeRTOS heap. xTaskCreateStatic() (with configSUPPORT_STATIC_ALLOCATION 1) takes arrays you declare, so the linker reports the total.

At run time, pick a heap. heap_1 never frees, so it cannot fragment: good for a system that creates everything at start-up. heap_4 frees and joins neighbouring free blocks. heap_3 wraps malloc(), heap_5 spans several RAM regions, and FreeRTOS keeps heap_2 only for old projects.

Call the stack depth of task i di, in words, and the size of one TCB sTCB. The RAM the tasks take is R:

Say it aloud

R equals the sum over i of, four times d-i plus s-TCB.

R
R the RAM all tasks take, in bytes.
Σi
the sum over i one term per task, the idle task included.
4
four bytes per stack word on a 32-bit Cortex-M.
di
d-i the depth passed to xTaskCreate(): words, not bytes.
sTCB
s-TCB one task control block: about 84 B in a lean build (illustrative; check sizeof(StaticTask_t)).
In plain words

Multiply each depth d-i by 4 for bytes, add one TCB s-TCB, and sum over the tasks. R must fit beside your globals and the interrupt stack.

With numbers

With made-up depths: stop 128, control 256, radio 384, logger 512, idle 128 words. Stacks: 1,408 × 4 = 5,632 B. TCBs: 5 × 84 = 420 B. R = 6,052 B, 29.6% of 20,480 B.

A stack must hold the deepest call chain plus the 64-byte parked context from Chapter 2. Measure it: FreeRTOS fills each new stack with the byte 0xA5, and uxTaskGetStackHighWaterMark() returns the least free space it ever had, in words. The logger's deepest chain, through snprintf(), is 1,700 B. With 64 B of context it uses 1,764 of 2,048 B, so the mark reads 71 words.

Overflow the logger, then catch it

The logger's stack grows down toward the radio's TCB. Purple still holds the 0xA5 paint, warm is in use, red lies past the end. Drag the deepest call, then pick a check.

1,700 B

Illustrative sizes. The deep call returns before the next switch; at each switch the stack holds 364 B. Method 2 checks the last 16 B in today's kernel source (the Kernel Book says 20 B).

Method 1 (configCHECK_FOR_STACK_OVERFLOW 1) tests the saved stack pointer at each switch, so a deep call that returns before the switch slips past. Method 2 also tests that the paint at the far end is intact, so it catches the damage, but only at the next switch. A memory protection unit (MPU) guard region below the stack faults on the first bad write; Zephyr calls this CONFIG_HW_STACK_PROTECTION, and its CONFIG_STACK_SENTINEL works like method 2.

Symptom: the radio task crashes hours apart, always after a long log line.

Measure: turn on method 2; vApplicationStackOverflowHook() names the logger, not the radio.

Fix: size each stack from its high-water mark plus a margin, and move big buffers off the stack.

A deep call overflows the stack and returns before the next context switch. Which check reports it?

Chapter 8

Two Kernels, One Shape

Write the stop task in FreeRTOS and in Zephyr, and map three priority scales

FreeRTOS and Zephyr name things differently, but the objects match one for one: a task or thread, a periodic wait, a queue, a semaphore given from an interrupt, a mutex with inheritance. Here is the same stop task in both.

c · FreeRTOS
SemaphoreHandle_t stopSem, spi;
void vStop(void *arg) {
  for (;;) {
    xSemaphoreTake(stopSem, portMAX_DELAY);
    if (xSemaphoreTake(spi, pdMS_TO_TICKS(5))) {
      drive_ramp_down();
      xSemaphoreGive(spi);
    }
  }
}
stopSem = xSemaphoreCreateBinary();
spi     = xSemaphoreCreateMutex();
xTaskCreate(vStop, "stop", 128, NULL, 4, NULL);
/* ISR: xSemaphoreGiveFromISR + portYIELD_FROM_ISR */
c · Zephyr
K_SEM_DEFINE(stop_sem, 0, 1);
K_MUTEX_DEFINE(spi);
void stop_fn(void *a, void *b, void *c) {
  for (;;) {
    k_sem_take(&stop_sem, K_FOREVER);
    if (k_mutex_lock(&spi, K_MSEC(5)) == 0) {
      drive_ramp_down();
      k_mutex_unlock(&spi);
    }
  }
}
K_THREAD_DEFINE(stop_tid, 512, stop_fn, NULL, NULL, NULL,
                1, 0, 0);   // stack in bytes; priority 1
/* ISR: k_sem_give(&stop_sem) is ISR-safe */

Three differences bite. FreeRTOS gives the stack in words; Zephyr's macros take bytes. FreeRTOS has separate FromISR calls; Zephyr marks which calls are safe from an interrupt. And the priority numbers run in opposite directions.

In FreeRTOS a higher number is more urgent and 0 is idle. In Zephyr a lower number is more urgent, and a negative number makes a cooperative thread, which keeps the core until it blocks. The NVIC agrees with Zephyr: lower is more urgent.

Line up three priority scales

Left is most urgent on every line. Interrupts sit above all tasks. Drag the kernel's interrupt limit and see which handlers may call the kernel, and which the kernel can never delay.

5

Illustrative assignments. The NVIC number is the priority in the STM32F103's 4 bits; the register holds it shifted left by 4.

The limit lives in the top 4 bits of an 8-bit field on this chip. So you write a limit of 5 as 5 × 16 = 80 (0x50) in configMAX_SYSCALL_INTERRUPT_PRIORITY. The button at priority 6 is register value 96, below the limit in urgency, so it may give the semaphore. Zephyr adds devicetree and Kconfig to describe the board; Zephyr in Practice builds one.

Symptom: after a port from FreeRTOS to Zephyr, the stop task runs last.

Measure: list the thread priorities: the stop task kept its FreeRTOS number 4, which in Zephyr is less urgent than the logger's 1.

Fix: map by rank, not by number: write down the order from most to least urgent, then number it in the new kernel's direction.

configMAX_SYSCALL_INTERRUPT_PRIORITY is 5 on a 4-bit NVIC. Which handler may call xQueueSendFromISR()?

Chapter 9

Run the Node, Then Plant Faults

Run four tasks for 200 ms, plant one-line faults, and name each by what it does to the timeline

Here is the whole node. The stop task (priority 4) waits for the button's semaphore and then needs the SPI bus for 0.5 ms. Control (priority 3) runs 2 ms every 10 ms with xTaskDelayUntil(). The radio (priority 2) sends a 15 ms burst every 100 ms. The logger (priority 1) writes flash over SPI every 50 ms, holding the bus mutex for 4 ms. Each press lands 1.37 ms into a log write, the worst place for it.

Run the node, plant a fault

Lanes show 200 ms; the playhead sweeps it. Pink marks are presses, yellow ticks the control loop's 10 ms marks. Plant faults alone and together, and read the counters.

Illustrative task set, simulated in 10 µs steps with no switch cost; one sweep of the playhead takes 8 s, 40 times slower than real time. The overflow check is method 2.

Read each fault by its shape. The semaphore turns a 3.63 ms stop into 22.63 ms: the radio burst and two control runs sit inside the wait, a deadline miss on every press. vTaskDelay(10) stretches control to a 12 ms period, 16 runs in 200 ms instead of 20. The missing yield holds the stop task Ready until the next tick, 0.63 ms after each press; its finish moves only 0.5 ms later, because the logger uses that time to get on with its write. The small stack trips the overflow hook once per log write, and the hook names the logger.

The design that passes uses every chapter. Control waits until an absolute tick. The bus has a mutex with short holds. The handler cuts the motor, gives a semaphore and yields. Every stack comes from its measured mark, and the 20 kHz current loop runs above the kernel's limit, untouched.

Chapter 10

Field Guide

Keep the numbers, the bugs, the whole series and the choice of kernel in one place

An RTOS gives each job a task: a loop with a stack, a priority and the right to block. The tick finds who is due, and PendSV parks one task in 16 words and wakes another. Queues copy data between tasks; semaphores signal; mutexes guard, and lend their priority so a low task cannot hold a high one behind a medium one. Handlers do the urgent part and wake a task with a yield. You measure and check every stack. Then the scheduling tests of Lesson 6 apply, with the blocking term B added.

QuantityRuleExample
Period with vTaskDelayT ≈ C + N · ttick3 + 10 = 13 ms: 76.9 runs/s
Context saved per task8 hardware + 8 PendSV words64 B
Kernel share(ftick ctick + fsw csw) / f0.69% at 1 kHz
Queue lengthN ≥ ⌈W / Tp⌉7.5 ms, 1 ms: 8
Lost updatesL ≈ n · w / k375 of 1,000
Blocking, inheritanceB ≤ min(n, m) · zmax≤ 6 ms; ceiling ≤ 3 ms
Deferred latencytISR + tsw + (1 − y) Ttick4.78 µs, or up to 1,004.78 µs
Task RAMΣ (4 di + sTCB)6,052 B of 20,480
BugSymptomWhat names it
Busy-wait in a superloopevery job slow during one slow eventloop period equals the wait
vTaskDelay for a periodloop slow by a fixed shareperiod = work + delay
Delay shorter than a ticka delay that never waitspdMS_TO_TICKS returns 0
Queue too shortdata gaps during burstserrQUEUE_FULL count
Unlocked read-modify-writecounts a little low, rarely on the benchfails under heavy preemption
Locks taken in two orderstwo tasks stop for goodeach Blocked on the other's mutex
Binary semaphore as a lockurgent task late under loadtrace: medium tasks run inside its wait
Missing portYIELD_FROM_ISRtask starts 0 to 1 tick latedelay spread evenly over a tick
API call above the limitrare kernel corruptionconfigASSERT in the port fires
Stack too smallanother task's data corruptedoverflow hook, high-water mark near 0
Priority numbers copied in a porturgent task runs lastFreeRTOS and Zephyr scales reversed

The series in one table

Each lesson of the series gave this one a piece. Keep this table as the map.

LessonWhat it gaveWhere the RTOS uses it
1. Embedded Systemstimers, interrupts, the superloop and its worst wait, a 10 ms stop deadlinethe tick is a timer; the superloop is Chapter 0's baseline; the ISR hands off in Chapter 6
2. Embedded Cwhere every byte lives, volatile, sharing data with an interrupt, the watchdogtask RAM in Chapter 7, the race in Chapter 4, a watchdog fed after every task checks in
3. Hardware Designthe power budget and the radio's cost per reportthe idle task can sleep; FreeRTOS tickless idle stops the tick while nothing is due
4. Hardware InterfacingSPI, I²C and UART on the wireone mutex or one gatekeeper task per shared bus (Chapters 4, 5)
5. Embedded Linuxa bigger chip with drivers, files and a network, and a latency tailthe choice below: Linux for the network and the screen, the MCU for the hard loop
6. Real-Time Systemsthe latency sum, NVIC nesting, the cyclic executive, rate monotonic and EDF, WCETscheduling tests with B added; ISRs above the kernel's limit; the cycle counter for c-switch

When not to use an RTOS

The scheduling theory this page leaves out lives in Lesson 6 (rate monotonic, EDF, the cyclic table) and The Real-Time Mental Model (the utilisation bound and the response-time test).

python
import math

def delay_period(C, N, tick=1.0):  return (math.floor(C / tick) + N) * tick   # vTaskDelay, released on a tick
def kernel_share(f_tick, c_tick, f_sw, c_sw, f): return (f_tick * c_tick + f_sw * c_sw) / f
def queue_len(W, Tp):                return math.ceil(W / Tp)
def lost_updates(n, w, k):           return n * w / k
def blocking_pip(n, m, z_max):       return min(n, m) * z_max
def deferred(t_isr, t_sw, T_tick, y): return t_isr + t_sw + (1 - y) * T_tick
def task_ram(depths, s_tcb=84):     return sum(4 * d + s_tcb for d in depths)

We ran each one. delay_period(3, 10) is 13.0. kernel_share(1000, 100, 2000, 200, 72e6) is 0.00694. queue_len(7.5, 1) is 8. lost_updates(1000, 3, 8) is 375. blocking_pip(2, 2, 3) is 6. deferred(2, 2.78, 1000, 0) is 1,004.78. task_ram([128, 256, 384, 512, 128]) is 6,052.

Keep going

Read next

The habit. For every lock, write down who takes it, for how long, and from what priority. For every handler, write down what it hands to which task, and whether it yields. If you cannot fill in the line, the kernel is deciding for you.
An urgent task misses only under heavy load. A trace shows medium tasks running while it waits on a lock that a low task holds. What is the fix?

Now teach it: press Present or Teach and explain why a mutex and a binary semaphore give the stop task 3 ms and 18 ms on the same bus. Then go back to the three tasks and predict the burst at which the semaphore misses before you drag.

Embedded Systems · Lesson 7: Embedded RTOS
Previous: Real-Time Systems · Back to Lesson 1 · Back to Gleams