A motor current loop runs 20,000 times a second, so each answer has 50 µs. The core enters the handler in 12 cycles, 0.17 µs. A 40 µs stretch with interrupts off, once every 2 ms in main, makes 102 of 20,000 answers late.
Pick how main protects its shared data, then drag the length of that critical section. Watch where each answer lands against the 50 µs line. Then we build, piece by piece, latency, timers, nesting, schedulers, measurement, jitter budgets and the watchdog.
You need Lesson 1's timers and interrupts and a little C. We build the rest from zero.
Lesson 6 of the Embedded Systems series. Before: Lesson 5, Embedded Linux. Next: Lesson 7, RTOS. Deadlines, tails and response-time analysis in depth: The Real-Time Mental Model. The hands-on track is Firmware from Zero.
Illustrative toy on an STM32F103 at 72 MHz. The 18 µs handler, the 1.17 µs conversion and one critical section every 2 ms (at a seeded random time) are toy numbers. Interrupt entry is 12 cycles on a Cortex-M3 with zero-wait-state memory (Arm).
Chapter 0
Follow one sample of a motor current loop, and see what a late answer costs
A brushless motor drive switches its transistors with PWM at 20 kHz. Once per period, a timer starts an ADC conversion of the motor current. When the conversion ends, an interrupt handler runs a small controller and writes the new duty cycle into the timer's compare register, CCR.
The timer does not use CCR at once. It copies CCR into the live compare at the next update event, the moment the counter wraps. That is the deadline. A write before the wrap takes effect then. A write after the wrap waits a whole extra period.
The yellow ramp is the timer's counter; it wraps every 50 µs. Blue is the conversion and the PWM pin, warm is the handler, purple is the CCR write. Drag the handler's run time past the wrap.
Illustrative timing. Preloaded compare registers that load at the update event are how STM32 timers work (RM0008). The 1.17 µs conversion is 14 ADC clocks at 12 MHz.
Count the room. At 72 MHz, one 50 µs period holds 3,600 cycles. The conversion takes 1.17 µs, the core enters the handler in 0.17 µs, and an 18 µs handler is 1,296 cycles. The write lands at 19.3 µs, so 30.7 µs of the period are spare.
A late write does not crash anything. The motor runs the old duty for one more period, so that sample acts 100 µs after the ADC took it, not 50. A controller tuned for one delay now sees two (Chapter 7 prices that). This is a hard deadline in the sense of hard, firm and soft: the answer must exist every period.
Symptom: the motor whines, and the current ripple grows at one load and not another.
Measure: set a spare pin high at the handler's first line and low after the CCR write. On a scope triggered by the PWM, the pulse's far edge must stay left of the wrap.
Fix: find what pushes the edge right. The rest of this lesson names every cause.
Chapter 1
Add up everything between the interrupt request and the handler's first line
Interrupt latency is the time from an interrupt request to the first instruction of its handler. Arm gives 12 cycles on a Cortex-M3 or M4 with zero-wait-state memory, 0.17 µs at 72 MHz. In that time the core stacks eight registers and fetches the handler's address.
That is a floor. Four things sit on top of it, and three are your code.
Call the hardware entry tent and the wake-up time from a deep sleep mode twk. Call B the blocking: the longest time a masked section, or a handler at the same priority, holds this interrupt back. Call I the interference: the run time of every higher-priority handler that can fire first. The worst latency is L:
L equals t-ent plus t-wake plus B plus I.
Start with the 12-cycle entry t-ent. Add the wake-up t-wake if the core sleeps deeply. Add the longest blocking B and every higher handler I. The sum L must fit the spare time in the period.
With made-up numbers: t-ent is 0.17 µs with no deep sleep. B is 40 µs of interrupts off in main. I is a 12 µs speed loop set above the current loop. L = 0.17 + 0 + 40 + 12 = 52.2 µs. The loop allows 50 − 1.17 − 18 = 30.8 µs of latency, so the write misses the wrap.
Each block is one term of L. The yellow line is the 30.8 µs this loop can spare. Turn the causes on and off, and drag the length of the interrupts-off section.
Illustrative values. The 12-cycle entry is Arm's figure for zero-wait-state memory. The 5 µs Stop wake-up stands for a few microseconds; read your part's datasheet table. The UART handler (2 µs) and the speed loop (12 µs) are toy numbers.
The core cuts the cost when handlers meet. With tail-chaining, a pending handler starts 6 cycles after the last one ends, with no unstack and restack. With late arrival, a more urgent request that comes during the stacking takes over the new frame.
The biggest term is usually B, and you choose it. __disable_irq() sets PRIMASK and masks every interrupt. On a Cortex-M3 or M4, BASEPRI masks only the interrupts at or below a priority you name. The priority-0 current loop then runs straight through the section. That is the hero's third design.
c /* STM32F103: 4 priority bits, in the top half of each 8-bit field */ uint32_t old = __get_BASEPRI(); __set_BASEPRI(1u << 4); // mask priorities 1..15; priority 0 still runs copy_telemetry(&shared, &local); __set_BASEPRI(old);
Symptom: the current loop is late about 100 times a second, at random.
Measure: toggle one pin around every __disable_irq() section and another around the handler. The late handlers start at the falling edge of the first pin.
Fix: use BASEPRI where the fast loop does not share the data; slice the rest.
Chapter 2
Price each handler as a share of the CPU, and find the event a slow handler loses
A timer counts in hardware, so its update events come exactly on time (Lesson 1 sets PSC and ARR). The jitter starts when software joins in. So let hardware do the timed part. The timer's trigger output can start the ADC directly, and the sample lands at the same instant every period, no matter how busy the core is.
The handler is the part that can fall behind. Every run costs its own code plus the entry and the return. How much of the CPU do the handlers take? Call each handler's rate fi, its run time Ci, and the entry plus return tovh. The share is U:
U equals the sum over i of f-i times, C-i plus t-overhead.
For each source, add the overhead t-overhead to the run time C-i. Multiply by the rate f-i. Add the sources. U is the share of the core that main never sees.
With made-up handlers: current loop 20,000 × (18 + 0.33) µs = 0.367. Speed loop 1,000 × 12.33 µs = 0.012. UART at 115,200 baud, 11,520 bytes a second × 2.33 µs = 0.027. U = 0.406, so main gets 59% of the core.
Yellow ticks are timer events every 50 µs. Warm blocks are the handler. The purple lane is the NVIC's pending bit: one bit, so it holds one waiting event. Drag the handler time past the period.
Illustrative: one 20 kHz source alone, 0.33 µs of overhead per run, 2,000 events counted. One pending bit per interrupt is how the NVIC works (Arm).
When the handler takes longer than its period, U for that one source passes 1. The next event sets the pending bit while the handler still runs. The one after that finds the bit already set, and the NVIC cannot count to two. That event is gone, with no error anywhere. At C = 55 µs, 9.6% of events vanish: 1 − 50 / 55.33.
So keep handlers short and move the slow work out. Three shapes work. Set a volatile flag for main. Push a byte into a ring buffer. Or let DMA fill one half of a buffer while main reads the other.
c void TIM1_UP_IRQHandler(void) { // update event: the ADC already started in hardware TIM1->SR = ~TIM_SR_UIF; // clear the flag first if (busy) overruns++; // count what the pending bit cannot busy = 1; current_loop(); busy = 0; }
Symptom: a counter driven by an interrupt runs slow, by a few percent, only under load.
Measure: compare the handler's run count with the timer's own count over one second, or check the peripheral's overrun flag (a UART sets ORE).
Fix: shorten the handler below its period with margin, or let DMA take the data.
Chapter 3
Give three handlers priorities, fire them together, and read the latency and the stack
The NVIC is a fixed-priority preemptive scheduler in hardware. A lower number is more urgent. A more urgent request preempts the code that runs. The running handler stops, a new frame goes on the stack, and the urgent handler runs. A request at the same priority waits for the running handler to finish. The STM32F103 has 4 priority bits, so 16 levels.
The UART fires at 4 µs, the speed loop at 5 µs, the current loop at 7 µs. Pick a priority scheme and watch who runs, and how deep the stack goes.
Illustrative run times (UART 2, speed 12, current 18 µs) and stack use. Entry 12 cycles and tail-chaining 6 cycles are Arm's figures; the 12-cycle return to a preempted handler is illustrative.
Give the shortest deadline the most urgent priority and the current loop starts 0.17 µs after its request, whatever else runs. Put everyone at one level and the current loop waits behind the speed loop for 11.3 µs. Priority order is a latency decision.
Each level of nesting stacks another frame. On a Cortex-M3 the hardware frame is 8 registers, 32 bytes, plus 4 bytes of padding if the stack pointer needs aligning. Handlers at the same level never nest, so count one handler per level: the one with the deepest stack. Call main's own peak Smain and the deepest handler's stack at level k sk. The worst stack is Smax:
S-max equals S-main plus the sum over k of, thirty-two plus s-k.
Take main's peak S-main. For every priority level that can nest on top, add a 32-byte frame and the biggest handler s-k at that level. The total S-max is what the stack must hold.
With made-up sizes: main 400 B; UART 48, speed 96, current 64 B. By deadline, all three nest: 400 + 80 + 128 + 96 = 704 B. All equal, only one runs at a time: 400 + 32 + 96 = 528 B.
Symptom: a hard fault, hours apart, always with global variables near the stack corrupted.
Measure: fill the stack with a pattern at boot, run the worst load, and find the lowest address that changed (stack painting).
Fix: size the stack for S-max with margin, and use fewer preemption levels: handlers that can wait share a level.
Chapter 4
Build the table of frames by hand, and find what a non-harmonic period does to it
The oldest real-time design has no scheduler at run time. One timer interrupt marks each minor cycle, a frame of fixed length. A table says which tasks run in each frame. After the last frame, the table starts again: that repeat is the major cycle. This is the cyclic executive, which Buttazzo calls timeline scheduling. Flight software used it for decades, because every run is the same run.
With periods T1 to Tn, the minor cycle is their greatest common divisor, and the major cycle their least common multiple. How many frames does the table need? Call that count F:
F equals the L-C-M of T-one to T-n, divided by the G-C-D of T-one to T-n.
Find the major cycle, the L-C-M of the periods. Find the minor cycle, their G-C-D. Divide one by the other. F is how many rows you write in the table.
With made-up periods 1, 5 and 10 ms: lcm 10 and gcd 1, so F = 10 frames of 1 ms. Add a task every 7 ms: lcm 70, so F = 70.
Each column is one 1 ms frame; the yellow line is its length. Grow task C, then spread the start frames. Then add a fourth task every 7 ms and count the frames.
Illustrative tasks: A runs 0.2 ms every 1 ms, B 0.3 ms every 5, C every 10, D 0.3 ms every 7. Spreading starts B in frame 1, C in 2, D in 3.
The design work is the packing. With every task starting in frame 0, frame 0 holds A, B and C. At C = 0.7 ms that is 1.2 ms in a 1 ms frame: an overrun, and every later frame starts late. Move C's first run to frame 2, and the busiest frame holds 0.9 ms. A task too long for any frame must be cut into pieces by hand.
On a microcontroller this is a timer and a switch. The timer handler sets a flag every millisecond; main runs that frame's row and sleeps with WFI until the next tick. Overrun detection is one line.
c void SysTick_Handler(void) { if (tick) overrun++; tick = 1; } for (;;) { while (!tick) __WFI(); // sleep until the frame starts tick = 0; for (int i = 0; table[frame][i]; i++) table[frame][i](); frame = (frame + 1) % F; }
Symptom: a small feature added to one task makes an unrelated task late, every 10 ms exactly.
Measure: log the overrun counter and the frame number where it rose.
Fix: move that task's run to a lighter frame, or split it. Re-check every frame, because the table is global.
Chapter 5
Run two tasks under both rules on one core, and see which one each rule lets down
A cyclic table fixes everything before the chip ships. A preemptive scheduler decides at run time: the most urgent ready task runs, and it may interrupt a less urgent one. On a Cortex-M you already own one. Give each periodic task its own timer interrupt and NVIC priority, and the hardware schedules them.
The usual rule is rate monotonic: the shorter the period, the higher the fixed priority. The Real-Time Mental Model derives its utilisation bound (0.828 for two tasks) and the exact response-time test. The other rule is EDF, earliest deadline first: always run the job whose deadline is nearest.
Task 1 needs 2 ms every 5 ms; task 2 needs C2 every 7 ms. Yellow ticks are deadlines. Red is work done after its deadline. Switch the rule, then drag C2 up.
Illustrative task set, simulated in 0.01 ms steps, both released at 0, no switching cost. A late job keeps running until it ends.
EDF has an exact test. Call each task's worst run time Ci and its period Ti, with each deadline equal to its period:
U equals the sum over i of C-i over T-i, and it must be at most one.
Divide each run time C-i by its period T-i and add the shares. If U is at most one, EDF meets every deadline. If U is above one, no rule can.
With the device's tasks: U = 2/5 + 4/7 = 0.400 + 0.571 = 0.971. That is at most one, so EDF meets every deadline. It is above the 0.828 bound, and rate monotonic misses: task 2's first job ends at 8 ms, 1 ms late.
EDF is not free. Under rate monotonic, task 1 starts at its release every time. Under EDF its start moves by 0 to 2 ms, because task 2 sometimes holds the nearer deadline. For a control loop that start is the sampling instant, so EDF trades deadlines for jitter. In overload, at C2 = 5 ms, rate monotonic still protects task 1, while EDF lets both tasks miss. Buttazzo calls this the domino effect.
The NVIC has fixed priorities, so EDF on a microcontroller needs a software scheduler, as in an RTOS (Lesson 7).
Symptom: after a port to fixed priorities, a 97% busy system misses in its slow task.
Measure: compute U and compare it with the rate-monotonic bound; then run the exact response-time test from The Real-Time Mental Model.
Fix: cut C so U drops below the test, make the periods harmonic (fixed priority then reaches 100%), or schedule by deadline.
Chapter 6
Time a handler with the cycle counter, and find the path that a bench test never runs
Every test so far needs C, the worst-case execution time (WCET): the longest the code can ever run, alone, on this chip. Three tools give a number: a pin on a logic analyser, the core's cycle counter, and static analysis of the binary. The first two measure; only the third bounds.
The Cortex-M3 and M4 carry a 32-bit counter, CYCCNT, in the DWT debug block. It counts every core clock. Read it before and after, and subtract with wrap-around. Call the start reading c0, the end reading c1, and the core clock f. The elapsed time is Δt:
Delta-t equals c-one minus c-zero, mod two to the thirty-two, divided by f.
Subtract c-zero from c-one in unsigned 32-bit arithmetic, so a wrap in between still gives the right count. Divide the cycles by f. The result is delta-t.
With made-up readings: c-zero = 4,294,960,000 and c-one = 1,000, so the counter wrapped. The difference mod 232 is 8,296 cycles, and 8,296 / 72 MHz = 115.2 µs. The counter wraps every 232 / 72 MHz = 59.65 s.
c CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // power the trace block (DEMCR bit 24) DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // start counting (bit 0) uint32_t c0 = DWT->CYCCNT; current_loop(); uint32_t dt = DWT->CYCCNT - c0; // unsigned: wraps correctly if (dt > worst) worst = dt; // keep the high-water mark
Bars count handler runs by time. The purple line is the observed maximum; the dashed line is the true worst case, the saturation path. Pick how many runs, and what inputs drive them.
Illustrative handler: 1,296 cycles plus 0 to 60 for branches, and a saturation path of 1,152 more cycles when the current command hits its limit. Each test uses a new seed.
A measured maximum is a lower bound on the WCET. The bench never drove the controller into saturation, so the 34.8 µs path never ran. Now let field inputs saturate 1 run in 5,000. A 10,000-run test meets the slow path with probability 1 − (1 − 1/5,000)10,000 = 86.5%; a 100-run test, 2%. Coverage decides the number.
The core adds its own variation. On a Cortex-M3 a branch costs a pipeline refill and a divide takes 2 to 12 cycles depending on the operands (Arm's Cortex-M3 manual). Flash wait states move fetch times too. So drive every path on purpose, account for preemption, and add a margin.
Symptom: the budget said 19 µs; in the field, late writes cluster when the motor accelerates hard.
Measure: keep the CYCCNT high-water mark in RAM and read it after a hard drive cycle. Then step the input to saturation on the bench.
Fix: budget the slow path. Write a test that forces each branch, and keep a margin above the observed maximum.
Chapter 7
Turn a delay into lost phase margin, and set the jitter budget from it
A controller corrects an error it measured some time ago. Push the delay far enough, and each correction arrives in step with the error it should cancel. The loop rings, then oscillates.
Control engineers call the room for delay the phase margin. It is the extra lag, in degrees, that the loop takes at its crossover frequency, where it stops amplifying. A pure delay adds lag in proportion to frequency. Call the crossover fc and the delay τ. The lag it adds is φ:
Phi equals three hundred sixty degrees times f-c times tau.
A delay tau shifts a sine wave at f-c by the fraction f-c times tau of one cycle. Multiply that fraction by 360 degrees. Subtract phi from the phase margin the design had.
With f-c = 1 kHz: holding each duty for a 50 µs period acts like a delay of half a period, 25 µs, so 9°. Applying the duty at the next update adds 50 µs, 18°. Together τ = 75 µs costs 27°. One missed update adds 50 µs more: τ = 125 µs costs 45°.
The pink line is the motor current answering a step in the command; the dashed line is the command. The bar shows the 90° this toy loop starts with, minus what the delay takes. Drag the delay through the marks.
Illustrative loop: an integrator with crossover 1 kHz and a pure delay, so its phase margin is 90° minus the lag. Simulated in 0.2 µs steps. Real current loops start with less margin than 90°.
This gives the jitter budget. Suppose the design must keep at least 45°. This toy loop starts at 90°, so delay may take 45°: τ up to 125 µs. The hold and the next-update write already use 75 µs. That leaves 50 µs for everything Chapters 1 to 5 add: one missed update, and nothing else. A loop that starts at 60°, not 90°, has no room for even one.
Use the worst delay, not the average, because the loop meets the worst one at random. Varying delay also hurts on its own, even with the average fixed; Same Mean Rate, Opposite Fate shows why. So make the delay short and constant. Trigger the ADC from the timer, run the loop at the top priority, and write CCR well before the wrap.
Symptom: the current loop rings after steps, but only when telemetry is on.
Measure: histogram the sample-to-write time from the pin pulses. Convert the worst one to degrees at your crossover.
Fix: remove the delay source (the masked section, the wrong priority), or lower the crossover until the margin holds.
Chapter 8
Set the timeout from the worst clock, and kick it only when every task has checked in
Everything so far assumes the code keeps running. A loop can wait on a flag that never comes, or a bus can lock up. A watchdog is a down-counter that resets the chip when it reaches zero. Healthy firmware reloads it in time, which is called a kick. Hung firmware does not, and the chip restarts into a safe state.
The STM32F103's independent watchdog (IWDG) runs from its own low-speed RC oscillator, the LSI, so it keeps counting when the main clock fails. Once started, software cannot stop it. Call the prescaler setting PR, the reload value RL and the LSI frequency fLSI. The timeout is twd:
t-w-d equals four times two to the P-R, times R-L plus one, divided by f-L-S-I.
Divide the LSI by the prescaler to get the tick rate. Count RL + 1 ticks. The time that takes is t-w-d, and it moves with the LSI.
PR = 1 (divide by 8) and RL = 999: 8 × 1,000 / 40,000 = 200 ms. At 60 kHz it is 133 ms; at 30 kHz, 267 ms. So kick at least every 133 ms. A hang ends within 267 ms.
The yellow ramp is the watchdog counter; teal ticks are kicks. Purple dots are the three tasks checking in. Pick where the kick lives, then hang the logger at 0.4 s.
Illustrative: PR = 1, RL = 999, a reboot of 50 ms. The 30 to 60 kHz LSI range is from the STM32F103 datasheet; the formula from RM0008.
Where the kick lives decides what the watchdog can see. A kick from a timer interrupt proves only that the timer and the NVIC work. A hung logger, or a main loop stuck in a while, leaves that interrupt running, so it kicks forever. Kick from main, and only after every task has set its check-in flag since the last kick.
The kick period must fit the fastest LSI. At 150 ms with RL = 999 and PR = 1, a part whose LSI runs at 60 kHz resets itself every 133 ms while healthy. The window watchdog (WWDG) adds the other bound. A kick that comes too early also resets, so code that runs wild and kicks in a tight loop gets caught.
c IWDG->KR = 0x5555; IWDG->PR = 1; IWDG->RLR = 999; // unlock, divide by 8, 1,000 ticks IWDG->KR = 0xCCCC; // start: cannot be stopped now /* main loop, every 100 ms: */ if (checkin == ALL_TASKS) { checkin = 0; IWDG->KR = 0xAAAA; } // kick
Symptom: a device in the field resets every few hours; the bench unit never does.
Measure: read the reset-cause flags in RCC_CSR at boot (IWDGRSTF names the watchdog) and log them. Measure that unit's LSI against a timer.
Fix: set the timeout for the fastest LSI with margin over the worst kick gap, including the longest flash erase.
while. The watchdog is kicked from the SysTick handler. What happens?Chapter 9
Run the current loop, the speed loop, the logger and the watchdog together, and name each fault by its symptom
Here is the drive. The current loop runs at 20 kHz at priority 0 and needs 18 µs, or 34.8 µs when the command saturates. A 35 µs speed loop runs at 1 kHz at priority 1. The logger in main copies telemetry every 2 ms. The watchdog times out after 200 ms. Each fault below is one line of code.
Top: the response time of every period in the last 20 ms, against the 50 µs line. Below: the motor current (pink) following its command (dashed). Step the command, then plant faults, alone and together.
Illustrative timing and a first-order motor current model; a late write holds the old duty for one more period. One second of the toy is one second of real time.
Read each fault by its shape. Interrupts off gives late periods at random times, about 100 a second, and more while the command saturates, because the slow path leaves less room. The swapped priority gives a late period every 20 periods, exactly 1 kHz: the period of the culprit is the period of the misses. Neither one breaks the watchdog. Hang the logger, and the watchdog resets the drive after 200 ms; kick in SysTick, and the drive keeps running with a dead logger that nobody notices.
The design that passes uses every chapter. The timer starts the ADC, not code. The current loop has the only priority-0 slot. BASEPRI guards shared data. The budget includes the saturation path. Main kicks the watchdog after every task checks in.
Chapter 10
Keep the numbers, the bug table and the next steps in one place
On a microcontroller the period is the deadline. The core enters a handler in 12 cycles; your masked sections, your priorities and your slow paths decide the rest. Price every handler as a share of the core, keep each one shorter than its period, and give the shortest deadline the top priority. Choose a table, fixed priority or EDF by what each costs. Measure the worst case with every path driven, turn delay into degrees, and let a watchdog fed by main catch the hang.
| Quantity | Rule | Example |
|---|---|---|
| Cycles per period | f · T | 72 MHz × 50 µs = 3,600 |
| Worst latency | L = tent + twk + B + I | 0.17 + 0 + 40 + 12 = 52.2 µs |
| Handler load | U = Σ fi (Ci + tovh) | 0.406 |
| Lost events | 1 − T / (C + tovh) when C + tovh > T | C = 55 µs: 9.6% |
| Worst stack | Smain + Σk (32 + sk) | 704 B |
| Cyclic table | F = lcm / gcd of the periods | 1, 5, 10 ms: 10; add 7 ms: 70 |
| EDF test | Σ Ci / Ti ≤ 1 | 0.971: passes |
| Cycle counter | ((c1 − c0) mod 232) / f | 8,296 cycles = 115.2 µs |
| Delay to phase | φ = 360° fc τ | 1 kHz, 125 µs: 45° |
| Watchdog timeout | 4 · 2PR (RL + 1) / fLSI | 133 to 267 ms |
| Bug | Symptom | What names it |
|---|---|---|
| Long interrupts-off section | random late periods | late starts line up with the section's end |
| Wrong priority order | late periods at the culprit's rate | the miss period equals a handler's period |
| Handler longer than its period | counts run slow under load | run count below the timer's count |
| Too many nesting levels | rare hard faults, corrupted globals | stack paint reaches the bottom |
| Cyclic frame overrun | unrelated task late at the major cycle | overrun counter and frame number |
| Bench-only WCET | misses during hard transients | high-water mark above the budget |
| Delay over budget | ringing after steps | worst sample-to-write time in degrees |
| Kick in an interrupt | hung task, no reset | kick code inside a handler |
| Timeout set at typical LSI | resets on some units only | IWDGRSTF set; that unit's LSI is fast |
python import math from functools import reduce def latency(t_ent, t_wk, B, I): return t_ent + t_wk + B + I def isr_load(srcs, t_ovh): return sum(f * (C + t_ovh) for f, C in srcs) def lost_share(T, C, t_ovh): return max(0.0, 1 - T / (C + t_ovh)) def worst_stack(s_main, levels): return s_main + sum(32 + s for s in levels) def frames(periods): lcm = reduce(lambda a, b: a * b // math.gcd(a, b), periods) return lcm // reduce(math.gcd, periods) def edf_ok(tasks): return sum(C / T for C, T in tasks) <= 1 def cycles(c0, c1, f): return ((c1 - c0) % 2**32) / f def phase_lag(f_c, tau): return 360 * f_c * tau def iwdg_timeout(pr, rl, f_lsi): return 4 * 2**pr * (rl + 1) / f_lsi
We ran each one. latency(0.17, 0, 40, 12) is 52.17. isr_load at the Chapter 2 rates is 0.406. lost_share(50, 55, 0.333) is 0.096. worst_stack(400, [48, 96, 64]) is 704. frames([1, 5, 10, 7]) is 70. edf_ok([(2, 5), (4, 7)]) is True. cycles(4294960000, 1000, 72e6) is 115.2 µs. phase_lag(1000, 125e-6) is 45. iwdg_timeout(1, 999, 60000) is 0.133 s.
Where it sits. A bare-metal design like this one holds a few loops and a logger. Past that, an RTOS runs each job as a thread with its own priority and stack, and the same latency, nesting and stack sums apply to it. A Linux board takes the network and the screen; the hard loop stays on the microcontroller beside it.
Now teach it: press Present or Teach and explain why a 12-cycle interrupt still misses a 50 µs deadline, and which three lines of code fix it. Then go back to the current loop and predict the late count at 32 µs before you drag.