A watchdog kicked from a timer interrupt never catches a hung program, because the interrupt keeps running. Move the kick to a health check and the hang is caught.
Break a robot joint’s firmware on purpose. Then learn how to catch the break, reach a safe state in time, and describe the whole thing in the words that safety standards use.
Choose where the watchdog kick lives, then press Inject the fault. Watch the clock: the time from fault to safe state reads out, or it reads “never caught”. Then we build each piece from zero.
You need a rough idea of what an interrupt is (a signal that pauses the main program to run a short handler) and a little C. We build the rest from zero.
This lesson is written from primary sources: the STM32F4 reference manual RM0383, the Linux kernel, the Memfault Interrupt blog and the Zephyr docs. The Field Guide at the end lists each one.
Pick where the kick lives and what breaks. Press Inject the fault to play 420 ms of firmware time.
A model, not real silicon. The watchdog timeout is 100 ms, tasks check in every 10 ms, the fault strikes at 200 ms. Reaction times (hold 60 ms, brake 30 ms, free 5 ms) are illustrative. The health task kicks only if every task and the command link checked in within 25 ms.
Chapter 0
See why a watchdog can sit in your firmware, run perfectly, and still miss the one hang it was bought to catch
A robot arm holds a one-kilogram tool above a bench. Its joint controller is a small chip running a loop: read the encoder, compute a torque, write the torque. One afternoon a bug sends the loop into a corner it never leaves. The torque stops updating. The arm sags, or swings on at the last command.
The team knew this could happen. They added a watchdog. The chip did not reset. Nothing barked. Why?
A watchdog timer is a hardware counter that counts down by itself. When it reaches zero it resets the whole chip. Your code stops the countdown by writing a magic value to it before it hits zero. Writing that value is called kicking the watchdog (some people say feeding or petting it).
Think of a dead man’s switch on a train. The driver must press a pedal every few seconds. If the driver stops, the train brakes. The pedal does not prove the driver is awake. It proves the driver’s foot is moving. A watchdog has the same weakness: a kick proves that the code which kicks is still running, and nothing more.
On the STM32F4 family, the reference manual RM0383 describes the independent watchdog (IWDG). It has its own slow clock, the low-speed internal oscillator (LSI), nominally 32 kHz, so it keeps counting even if the main clock fails. You unlock it by writing 0x5555 to its key register, set a prescaler and a 12-bit reload value, start it by writing 0xCCCC, and kick it by writing 0xAAAA. When the counter reaches 0x000 the chip resets.
The timeout is (reload + 1) times the prescaler divider, divided by the clock. We want 100 ms at 32 kHz.
timeout = (RL + 1) × divider / fLSI = 100 × 32 / 32,000 Hz = 100 ms
One honest caveat: the manual’s table assumes an exact 32 kHz. The real LSI drifts with temperature and from part to part. The datasheet gives its minimum and maximum, so your 100 ms is really a band. Plan for it.
c/* STM32F4: start the IWDG with a 100 ms timeout (RM0383, section 15) */ void wdg_start(void) { IWDG->KR = 0x5555; /* unlock PR and RLR */ IWDG->PR = 3; /* divide LSI by 32 */ IWDG->RLR = 99; /* (99+1) * 32 / 32000 = 0.1 s */ IWDG->KR = 0xCCCC; /* start counting down */ } static inline void wdg_kick(void) { IWDG->KR = 0xAAAA; } /* reload the counter */
Where do you call wdg_kick()? The easiest place is a periodic timer interrupt, because it fires on schedule. It is also the worst place. An interrupt service routine (ISR) runs even when the main loop is stuck in a while(1), because the hardware calls it. The kick keeps coming. The counter never reaches zero.
The fix is to kick from the result of checks. A small health task runs at the lowest priority. Each important task writes a check-in time. The health task kicks only if every check-in is recent. If one task hangs, its check-in goes stale and the kick stops. If a hung task hogs the CPU, the low-priority health task never runs, so the kick stops for that reason too. Memfault’s watchdog guide describes the same shape: feed the hardware only when all registered tasks have recently checked in.
Now try it. The hero at the top is the experiment. Put the kick in the timer ISR, hang the main loop, and read “never caught”. Then move the kick to the health task. The same hang is caught about 115 ms after the fault, because the last good kick came at 215 ms and the timeout is 100 ms. Run it again here with the kick in the main loop and the sensor task hung: the main loop is alive, so it keeps kicking, and the sensor fault goes unseen.
c/* each task calls checkin(id) once per loop; only the health task kicks */ static volatile uint32_t last_seen[N_TASKS]; void checkin(task_id id) { last_seen[id] = tick_ms(); } void health_task(void *arg) { /* lowest priority */ for (;;) { uint32_t now = tick_ms(); bool ok = true; for (int i = 0; i < N_TASKS; i++) if (now - last_seen[i] > MAX_AGE_MS[i]) ok = false; if (ok && link_age_ms() <= LINK_MAX_MS) wdg_kick(); vTaskDelay(10); } }
A hung program is not the only way to fail. A loop that spins far too fast, because a delay was skipped, kicks far too often and looks healthy to a plain watchdog. The window watchdog (WWDG) adds a rule: you may kick only inside a time window. Kick too early and it resets the chip. Kick too late and it resets the chip.
RM0383 gives the WWDG a 7-bit down-counter. It resets when the counter rolls over from 0x40 to 0x3F (bit T6 clears). A second register holds the window value W. A refresh while the counter is still above W also resets. One count lasts 4096 × 2WDGTB cycles of the APB1 clock.
The window is 36.7 ms to 49.9 ms. Slide the kick time and see it.
The bar is time since the last kick. Green is the allowed window. Drag the kick time and watch where it lands.
Numbers follow RM0383 section 16 with an assumed 42 MHz APB1 clock, WDGTB = 3, reload 0x7F, window 0x50. The part and clock are chosen for the example. A model of the timing, not a run on silicon.
On real hardware. Take an STM32 Nucleo-F4 board. Start the IWDG at 100 ms, then add while(1); to the main loop with the kick in a timer ISR. Measure how long the board takes to reset: it never does. Move the kick into a health task and measure the reset with a logic analyzer on the NRST pin, about 100 ms after the last kick.
while(1). A timer ISR kicks the watchdog every 10 ms. What happens?Chapter 1
Learn three words that split one bug into a chain, and a time budget that tells you how fast you must react
Two engineers review a design. One says, “If the encoder fails, the drive is fail-safe.” The other says, “If the encoder fails, the arm goes limp. That is not safe.” Both are right. They use “fail-safe” for different things. One means the drive stops commanding torque. The other means the load stays where it is.
The cure is vocabulary. A few exact words, agreed before the design starts, turn a heated argument into a table you can fill in.
The dependability literature (Avizienis, Laprie, Randell and Landwehr) splits one broken thing into three links. A fault is a defect: a cracked solder joint, a bit flipped by radiation, a bug in the code. An error is a wrong value inside the system caused by an active fault: the encoder reading says 0 while the shaft turns. A failure is the moment the system’s behaviour breaks its specification: the arm drives into the table.
Think of a leaking pipe in a wall. The crack is the fault. The damp patch spreading behind the plaster is the error. The ceiling that falls on the kitchen is the failure. You can act at every link. Fix the crack, spot the damp, or catch the ceiling.
One more rule from the same taxonomy: a failure of one part is a fault for the part that depends on it. The encoder fails, so the controller gets a fault. That is why chains can run long.
Fault tolerance is a race. The fault happens at time zero. Before the hazard can hurt anyone you must detect it and then react. ISO 26262, the road-vehicle standard, calls the allowed time the fault tolerant time interval (FTTI): the span from the fault to a possible hazardous event, if nothing intervenes. Your two jobs fit inside it:
fault detection time + fault reaction time ≤ FTTI
The detection time is how long the fault goes unseen. The reaction time is how long the system takes to reach the safe state, a condition in which the hazard cannot happen. The FTTI is set by physics, not by firmware. A falling arm sets it. A bursting battery sets it.
The bar runs from the fault at 0 to the hazard. Slide detection and reaction. The safe state must arrive before the red line.
Illustrative numbers for a robot joint. The FTTI idea is from ISO 26262; the standard text itself was not opened for this lesson, so check its exact definition before you cite it in a safety case.
The cure for the opening argument is a table written before the code. One row per fault. Each row names the detection and the safe state, in plain words.
| Fault | Detected by | Safe state | Allowed time |
|---|---|---|---|
| Encoder cable broken | Position frozen for 2 samples | Close brake, then cut torque | 30 ms detect + 30 ms react |
| Main loop hangs | Watchdog from a health task | Reset, drive boots with torque off and brake closed | Under 115 ms detect |
| Command link lost | Deadman timer (Chapter 2) | Controlled stop (Chapter 3) | Set by link period |
Teams that ship hardware near people use named methods to fill such tables. FMEA (failure modes and effects analysis) walks every part and asks “how can this fail, and what then?” FTA (fault tree analysis) works backward from a bad outcome to the combinations of faults that cause it. HARA (hazard analysis and risk assessment) lists the hazards and ranks them; Chapter 5 uses it. STPA, from Nancy Leveson’s Engineering a Safer World, looks at the control loops and asks which commands can be unsafe. The standards behind them are the subject of Chapter 5: ISO 26262 (road vehicles), IEC 61508 (the general parent), ISO 13849 (machine controls), and MISRA C, a coding guideline for C.
The 100 ms in the budget is not a guess to tune. It comes from the machine. Take the arm of Chapter 3, with its 0.5 m reach. At 2 rad/s its tip moves at 2 × 0.5 = 1 m/s, that is 10 cm in 100 ms. If a hand can be 10 cm from the tip, you have 100 ms before contact. If the hand can be 5 cm away, you have 50 ms, and the same firmware is now too slow. The FTTI is a property of the arm, its speed and its surroundings. Slow the arm down and the budget grows. This is the oldest trick in safety: when you cannot make the reaction faster, reduce the energy.
Here is the procedure for each row of the table, in order. First, name the hazard that the fault could cause. Second, find the time to that hazard from physics. Third, choose a detector and measure its worst-case detection time, including the wait for the next check to run. Fourth, choose the safe state and measure its reaction time. Fifth, add them and compare. If the sum is too big, you may change the detector, the safe state, or the physics.
Some faults do nothing until a second fault arrives. A brake that has quietly stopped working is one. The arm runs fine for months. The first time the controller faults, the brake that should have caught it does not close. This is a latent fault. The cure is a periodic self-test: close the brake at start-up and check that the shaft cannot move. A safe design lists, for each safety part, how a failure of that part would become visible, and how often it is tested.
On real hardware. Take any board with an encoder or a potentiometer on an ADC pin. Write down one fault (unplug the wire), its detector, and its safe state. Time the gap between unplugging and the detector firing with a GPIO toggle on a logic analyzer. That gap is your measured detection time.
Chapter 2
Watch a part you cannot touch by listening for its pulse, and tune how fast you notice versus how often you cry wolf
Your arm has six joints. Each joint is its own small chip, and they talk to a main controller over a bus. One joint chip locks up. It stops sending its position. The main controller still has a number for that joint: the last one it received. It is stale, and it looks real. The controller computes with it and the arm moves wrongly.
A local watchdog cannot save you here. It resets the chip that owns it. The main controller needs to know that a remote chip is alive. That is the job of a heartbeat.
A heartbeat is a short message each node sends at a fixed period, only to say “I am alive”. The listener, the consumer, keeps a timer. Each heartbeat restarts the timer. If the timer reaches a limit, the consumer declares the node dead. The idea is general. In CANopen, a heartbeat producer sends a frame whose identifier is 0x700 plus its node number, and one data byte holds its state (0x05 means operational, 0x7F pre-operational). The consumer’s timeout lives in its object dictionary.
Two numbers define a heartbeat scheme. The period P is how often a beat is sent. The missed count N is how many beats in a row you may lose before you declare death. The consumer’s timeout is N × P.
Say the node dies at some moment. The last beat arrived between zero and one period earlier. The consumer waits N × P after that last beat. So the time from death to the alarm lies between (N − 1) × P and N × P. The worst case is N × P.
worst detection latency = N × P
Speed seems free: shrink P and N. The price is false alarms.
Buses lose messages. A frame collides, a node is busy, noise corrupts a CRC. If each beat is lost with probability p, independently, then N beats in a row are all lost with probability pN. A run of N losses makes the consumer cry wolf although the node is fine. Over an hour, a node sends 3,600,000 / P beats. The number of false alarms per hour is about that, times (1 − p) times pN.
One more step in N cuts false alarms by 20 times and costs one more period of detection time. Tune with the sliders. The bus loss rate is a guess in this model, so measure it on your own bus.
Each tick is a beat. Red ticks are lost beats. The node dies at the dashed line. The green flag marks when the consumer notices.
Illustrative. Losses are drawn at random and independent, which real buses are not (noise comes in bursts). The latency formula is exact; the false-alarm rate is the formula above.
A heartbeat proves only what produces it. If a separate timer thread sends the beat, the beat says “the timer thread runs”. The control loop could be dead. This is the Chapter 0 mistake again, on a bus. The beat must be sent as the result of the work: after the control loop has finished an iteration and checked in with the health task. A good beat also carries a counter that increases by one. Then the consumer sees a frozen counter, a stuck sender that repeats old frames.
c/* producer: send the beat only if the health task says all is well */ void joint_loop_iteration(void) { read_encoder(); run_control(); write_torque(); checkin(TASK_CONTROL); if (health_ok()) can_send_heartbeat(++beat_counter, state); } /* consumer: a deadman timer, restarted by every good beat */ void on_heartbeat(uint8_t node, uint8_t counter) { if (counter != last_counter[node]) { last_seen_ms[node] = tick_ms(); last_counter[node] = counter; } } bool node_alive(uint8_t node) { return tick_ms() - last_seen_ms[node] <= N_MISSED * PERIOD_MS; }
The reverse direction needs the same care. The main controller sends torque commands to a joint. If the link dies, the joint must not hold the last command forever. A deadman timer on the joint says: if no valid new command arrives within a limit, go to the safe state. Each command carries a timestamp, and the joint rejects one older than its limit. Then a command delayed in a queue cannot act as if it were fresh. The latency budget behind those limits is the subject of the real-time lesson on deadlines and the sensor-to-actuator chain, robot real-time performance, and the bus itself is built in CAN and EtherCAT.
Consider how a delayed command becomes dangerous. The main controller sends a torque command at time 1,000 ms that says “push 3 N m”. A bus fault queues the frame. It reaches the joint at 1,090 ms. Without a timestamp the joint cannot tell the frame is 90 ms old, and it applies the push to a situation that has moved on. With a timestamp, the joint computes the age: 1,090 − 1,000 = 90 ms. Its limit is 30 ms, so it rejects the frame and counts a missed command. After the missed-command limit passes, the deadman timer sends the joint to its safe state.
This needs the joint and the controller to agree on the time. They share a clock source or keep a measured offset, and the offset itself becomes a number to check. If the clocks drift apart by 40 ms, every good frame would look stale. So the deadman design has three numbers to choose together: the command period, the age limit, and the missed-command count.
A good consumer tests all four, not only the first.
On real hardware. On two boards linked by CAN (or two UARTs), send a heartbeat at 20 ms. Unplug the wire. With a logic analyzer on a GPIO that the consumer toggles at the moment it declares death, measure the gap from the last beat. It should land between 40 ms and 60 ms for N = 3.
Chapter 3
Choose what the joint does once a fault is caught, and see why cutting power is sometimes the most dangerous answer
A person presses the big red emergency stop on a robot arm. The arm is holding a tool at arm’s length, and its joint is moving down. What should happen? “Cut the power” sounds right. Power is what moves things.
Cut the power to a joint that carries a load, and gravity takes over. The arm falls. For a vertical axis, no power is not the same as no motion.
Take a uniform rod arm: mass 2 kg, length 0.5 m, pivoting at one end. These are toy numbers. Its moment of inertia (how hard it is to spin) about the pivot is I = mL²/3 = 2 × 0.25 / 3 = 0.167 kg m². Gravity pulls with a torque of m g (L/2) at the horizontal position: 2 × 9.81 × 0.25 = 4.9 N m. A motor must supply 4.9 N m just to hold the arm still. Moving at 2 rad/s, the arm carries kinetic energy ½ I ω² = 0.5 × 0.167 × 4 = 0.33 J. Something must remove that energy, and something must keep holding the weight.
I = mL²/3 = 0.167 kg m² · hold torque = mg(L/2) = 4.9 N m · energy = ½ I ω² = 0.33 J at 2 rad/s
Machine standards give three stop categories. As they are usually summarised from IEC 60204-1: category 0 removes power to the actuators at once, an uncontrolled stop. Category 1 keeps power just long enough to bring the machine to rest under control, then removes it. Category 2 brings it to rest under control and keeps power on to hold position. I did not open the standard’s text for this lesson, so treat these as a summary and check the clause before you quote it.
A related term is safe torque off (STO): a function that ensures no energy able to produce torque reaches the motor and prevents it from starting by accident. STO is how a drive implements the “power removed” step. Notice what STO does not do. It does not hold a load. Only a mechanical brake, a part that clamps the shaft, holds a load with the power off.
| Policy | What happens | Needs working drive? | Holds a load? |
|---|---|---|---|
| Cut torque only (cat 0, no brake) | Torque disappears at once | No | No: the arm falls |
| Cut torque and close the brake (cat 0) | Brake clamps after its delay | No | Yes, after the delay |
| Controlled stop, then brake (cat 1) | Motor brakes the motion, then STO and brake | Yes | Yes |
Run the three policies on the arm above. The arm moves down at 2 rad/s. The fault is detected 20 ms after it begins; in those 20 ms the controller still drives the arm on. Then the stop starts. The brake takes 30 ms to close (illustrative) and clamps with 12 N m. The controlled stop uses at most 8 N m of motor torque.
The controlled stop wins on distance because it starts to slow the arm at once, but it needs a working drive. If the fault is the drive, you get the brake. A safe design plans for both: try the controlled stop, and have the brake as the backup that needs no power.
The arm starts horizontal and moves. Choose a policy and a speed (negative is downward), then press Fault!. The line behind the tip is its path.
A model: 2 kg uniform rod, 0.5 m, no friction at the pivot, no end stops, brake 12 N m after a 30 ms delay, controlled stop limited to 8 N m. The numbers are illustrative; take the real ones from your brake and motor datasheets.
The failure here has a clear symptom: an operator hits the E-stop and the arm drops onto the bench. The measurement is the dropped distance, as in the device. The fix is a layered stop: command a controlled stop first, close the brake, and only then remove torque (STO). A watchdog reset follows the same rule. After a reset, the drive firmware must come up with torque off and the brake closed. Never hand the load to nothing. Chapter 0’s watchdog and this chapter meet at that line: the boot code must set the safe output state before it does anything else (see from the vector table to main).
The motor control that does the controlled stop is in motor control firmware.
c/* a layered stop: controlled first, brake as backup, STO last */ void enter_safe_state(void) { drive_set_torque_limit(STOP_TORQUE_NM); drive_command_speed(0.0f); /* controlled deceleration */ timer_start_oneshot(BRAKE_DELAY_MS, brake_close); /* backup: needs no drive */ wait_until(speed_below(EPS) || timeout_ms(STOP_MAX_MS)); brake_close(); /* hold the load */ drive_sto(); /* torque off, last */ }
The brake torque has to beat the hold torque with a margin. Here the brake grips with 12 N m and the arm needs 4.9 N m to hold at the horizontal position, so the margin is 12 / 4.9 = 2.45 times. A brake rated below 4.9 N m would slip and let the arm creep down even when closed. That is a quiet failure: the brake is there and does not work. Real brakes are rated and tested for holding torque, so check the datasheet for the figure and check the brake with a periodic holding test (Chapter 1’s latent faults).
Next, ask what happens if the cause of the stop is the drive itself. A controlled stop uses the drive. If the drive has failed, the controlled stop cannot work, and the brake is the only thing left. That is why the code in this chapter starts a timer for the brake at the same time as it asks for the controlled stop. The brake closes at the timer limit even if the speed never reached zero. The price is a harder stop than planned. The gain is that no single fault leaves the arm free.
One more place the stop shows up: the boot. A watchdog reset restarts the chip, and for the first milliseconds the pins are not driven by your code. A motor driver pin that floats could enable the bridge. Good boards add pull resistors so that a floating enable means torque off and brake closed. Then the code sets the pins explicitly as its first act. The reset is safe because the hardware and the first line of software agree.
On real hardware. Use a small hobby servo arm or a stepper-driven lever on a Nucleo or an RP2040 board. Command a move, cut the driver’s enable pin, and film the arm at 240 fps. Count frames from the cut to rest. Repeat with a brake or a hold current.
Chapter 4
Write the checks that notice bad data, then break the system on purpose to learn which checks really run
A joint controller reads its angle from an encoder over SPI once every millisecond. One day the reading jumps from 41.2 degrees to 300 degrees and back within a single sample. The controller sees a violent error and slams the arm. Nothing was wrong with the arm. A single noisy frame fooled the code.
Data from the outside world cannot be trusted by default. Each value must prove it is believable before the control loop uses it.
A plausibility check asks whether a value could be true. Six cheap checks cover most of what goes wrong:
Memory can fail too. Some chips add ECC (error-correcting code) to flash and RAM so that a single flipped bit is corrected and a double flip is reported. Check your part’s reference manual for which memories have it.
c/* plausibility checks on one angle sample, called every 1 ms */ typedef enum { OK, F_RANGE, F_RATE, F_FROZEN, F_DISAGREE } fault_t; fault_t check_angle(float a, float b /* second sensor */) { static float prev; static int same; if (a < 0.0f || a > 360.0f) return F_RANGE; if (fabsf(a - prev) > MAX_STEP_DEG) return F_RATE; /* e.g. 5 deg per ms */ same = (a == prev) ? same + 1 : 0; if (same >= 30) return F_FROZEN; if (fabsf(a - b) > MAX_DISAGREE_DEG) return F_DISAGREE; prev = a; return OK; }
Detection should lead to a reaction with no human in the loop. The Linux kernel gives a neat small example. When a device raises an interrupt that no handler claims, the kernel counts it. In note_interrupt() (file kernel/irq/spurious.c), after every 100,000 interrupts on a line, it checks whether more than 99,900 of them were unhandled. If so, the interrupt is declared stuck, a report is printed, and the kernel logs “Disabling IRQ” and shuts that line off. A storm that would eat the whole CPU is cut off by a rule of two numbers.
In firmware the same idea protects a motor-fault pin that chatters. Count the interrupts per second. Above a limit, mask the line and enter the safe state, instead of letting the CPU drown in the ISR (see interrupts and DMA).
Here is the trap. You write all six checks. They never fire in testing. Do they work? You cannot know. A check that has never fired is a dead path: it might have a typo in the threshold, or be wired to the wrong variable, or be skipped by an #if. Safety code that was never exercised is a hope, not a defence.
Fault injection is the cure. You put the fault in on purpose and watch the reaction. Inject a stuck value into the encoder driver. Corrupt one byte of a frame. Drop ten frames in a row. For each injection the test asserts two things: the right check fires, and the system reaches the safe state inside the budget from Chapter 1. Try it below. Switch checks off to see which faults escape.
Rows are injected faults, columns are checks. Toggle checks, then press Run campaign. A green dot is a check that fired.
Which check can see which fault is a simplified rule table (for example, slow drift stays in range and under the rate limit, so only a second sensor sees it). Detection times are illustrative: a 10 ms frame, frozen after 30 samples, timeout after 30 ms, disagreement after 40 ms.
Run the full set: all five faults reach the safe state. Turn off the second sensor and drift escapes: nothing else can see a slow, in-range creep. That is the symptom. The measurement is the campaign table. The fix is the redundancy check, plus the habit of running the campaign on every build. Chapter 6 shows how.
Two sensors disagree a little even when both are fine, because of noise. Where do you set the limit? Suppose each encoder has independent noise with a standard deviation of 0.1 degrees (illustrative). The difference of two such readings has a standard deviation of 0.1 × √2 = 0.141 degrees. Set the limit at 0.5 degrees, which is 0.5 / 0.141 = 3.5 standard deviations.
This assumes independent Gaussian noise. Real noise has bursts and shared causes, such as a common power rail, so measure your own. The shape of the answer holds: a short debounce turns a noisy threshold into a quiet, fast check.
Independence matters as much as the threshold. Two encoders that read the same magnet through the same amplifier fail together, and the check sees agreement while both are wrong. This is a common-cause failure. Different sensing principles, separate wiring and separate power are the usual remedies.
On real hardware. On an STM32 Nucleo, use a second GPIO to pull the SPI MISO line high (a stuck-at fault) while the loop runs. Measure with a logic analyzer from the pull to the safe-state output. Repeat with a wire that you briefly disconnect (a timeout fault).
Chapter 5
Read ASIL, SIL and MISRA as plain engineering: how much risk to remove, and what you must write down to show you did
Your joint controller passes every test in the lab. A customer asks: “Can you show me it is safe enough to work beside people?” “It passed our tests” is not an answer. The customer wants to know which hazards you considered, how much risk each one carries, and what evidence ties each safety claim to your code.
That is what the functional-safety standards organise. They are not magic. They are a shared habit of thought, written down in long documents.
Functional safety means a system does the right thing when part of it goes wrong: a safety function (such as “stop the arm if the guard opens”) keeps working, or fails to a safe state. IEC 61508 is the general standard for electrical and electronic systems. ISO 26262 adapts it for road vehicles. IEC 62061 and ISO 13849 apply the same thinking to machine controls. ISO 26262 is “based on IEC 61508”; a rating such as ASIL or SIL applies to an end-to-end safety function, not to one chip or one file.
ISO 26262 starts with HARA, hazard analysis and risk assessment. You list the hazards. For each hazardous event you rate three things: severity S (how bad is the harm, S1 to S3), exposure E (how often is the situation present, E1 to E4) and controllability C (can a person avoid the harm, C1 to C3). The result is an ASIL, an automotive safety integrity level: QM (no safety requirement beyond ordinary quality) or A, B, C, D, with D the strictest. The top combination S3, E4, C3 gives ASIL D. Each step down in one factor lowers the level by one.
A handy way to compute it: add the three class numbers. Ten gives D, nine gives C, eight gives B, seven gives A, and less gives QM. The check against the standard’s own example: S3, E1, C3 sums to 7, and the ISO 26262 article on Wikipedia gives that example as ASIL A. The table is informative and leaves room for judgment, so teams argue each rating in review.
IEC 61508 speaks in SIL, safety integrity level 1 to 4. For a function that works all the time, each level is a band for the probability of a dangerous failure per hour (PFH):
A rate of 10−7 per hour is one dangerous failure per 10 million hours, about 1,140 years. These PFH values count random hardware failures. Software does not fail at random; it carries systematic faults, so the standards govern software through process rather than through a number.
Top: choose severity, exposure and controllability. Bottom: slide a dangerous-failure rate and see the SIL band it lands in.
The sum rule reproduces the S3/E4/C3 = D and S3/E1/C3 = A cases from the ISO 26262 summary. The decomposition options (for example D into B(D) + B(D)) are quoted from memory of ISO 26262 part 9 and were not checked against the standard text; confirm them before use. SIL bands are from IEC 61508 as summarised by TUV SUD and Wikipedia.
The higher the level, the more evidence. Typical items: a safety requirement for each hazard, traced down to code and tests; a design that keeps safety code apart from the rest; coding rules; static analysis; tests with measured coverage; and reviews with independence from the author. Do not read this as paperwork for its own sake. It is the proof that Chapter 4’s checks exist, run, and were tested.
MISRA C is a set of guidelines for writing C in safety work, published by the MISRA Consortium. Its categories are mandatory (always comply), required (comply unless a formal deviation is recorded) and advisory (good practice). MISRA C:2012 has 143 rules and 16 directives. A tool checks most rules automatically. It removes whole classes of C traps, such as unclear integer conversions.
Treating the standard as a checkbox fails. A high level changes the design. Common patterns: a dual channel, two independent computations that must agree; a monitor, a small simple part that checks a big complex one (the health task of Chapter 0 is the smallest version); and partitioning, where the memory protection unit stops non-safety code from touching safety data (see pipeline and privilege). ASIL decomposition lets two sufficiently independent parts share a high level: a D requirement can be met by two independent B parts. The word “independent” carries the weight. Two channels that share one clock or one power rail are not independent.
Two more names you will meet. SOTIF (safety of the intended functionality) covers hazards with no fault at all, such as a perception model that misreads a scene. STPA, from Chapter 1, suits systems whose behaviour depends on software and learning. For machine robots, ISO 13849 rates a control function with a performance level instead; the idea is the same.
What does the evidence look like? Take one hazard and follow it. Each line points to the next, so a reviewer can walk from the top to a test result.
If any line is missing, the claim is not shown. If a line changes, the lines below it are re-checked. This traceability is the most valuable thing the standards teach, and it is also the most tedious by hand, so teams keep it in tools and link requirements to tests.
Independence has a cost, and it also has a trap. ASIL decomposition is only valid if the two parts cannot fail together for the same reason. Check the shared things: one clock, one power supply, one compiler bug, one library. If a single cause can break both, the split gives no credit.
Chapter 6
Run every safety test on every commit, with a simulated robot wired to a real board, so a regression never reaches a real arm
On Friday a teammate tidies the control loop. All the unit tests pass. On Monday a joint in the field starts to jitter and, once, fails to brake. The change moved a function from RAM to flash, and the extra wait states pushed the loop past its 1 ms deadline on the real chip. A test that ran on a laptop could not see it.
A firmware bug is not like a web bug. A bad build can mean a physical unit someone must travel to service. The defence is to test on the same kind of chip, in the same timing, automatically, every time the code changes.
Think of four rooms, from cheap and fast to costly and real.
Notice the match with the earlier chapters. The watchdog placement bug of Chapter 0 shows up only where real interrupts and a real scheduler run, so SIL misses it and HIL catches it. The stop behaviour of Chapter 3 needs a plant model to measure how far the arm drops. Fault injection (Chapter 4) is easy in HIL because the rig sits on the wires.
HIL is slower, and you have fewer rigs than laptops. Plan with arithmetic. Say a test takes t seconds on its layer, you have n tests, and r rigs run in parallel.
run time = n × t / r
So you run the two-second set on every commit, and the five-minute set before a merge or overnight.
Choose a layer. Solid boxes are real, dashed boxes are simulated. Dots travel round the loop: sensor values forward, commands back.
Illustrative times per test: host unit 0.05 s, SIL 0.5 s, HIL 30 s, bench 300 s. Which bugs each layer can see is a simplified summary of the discussion in the text.
A test suite that covers only the happy path leaves the safety code unexercised, which is the dead-path trap from Chapter 4. Each safety requirement gets at least one test that injects its fault and asserts two things: the safe output is reached, and it is reached inside the time budget of Chapter 1. Then wire the suite into continuous integration (CI) as a regression gate: a merge is blocked if a safety test fails, or if a safety test is deleted. This is the same discipline as in regression testing for ML: a fixed set of cases, a threshold, and a gate that stays closed on a miss. The wider craft of host tests, emulators and rigs gets a full lesson in testing firmware without the board.
c/* a HIL test: hypothetical rig API (hil_*), real assertion logic */ void test_stuck_encoder_reaches_safe_state(void) { hil_reset_dut(); hil_run_ms(500); /* arm moving, all healthy */ uint32_t t0 = hil_now_us(); hil_inject(FAULT_ENCODER_STUCK); /* the rig freezes the encoder signal */ TEST_ASSERT_TRUE(hil_wait_for_pin(BRAKE_CLOSE, HIGH, 100000)); TEST_ASSERT_LESS_THAN(60000, hil_now_us() - t0); /* detect + react < 60 ms (Ch 1) */ TEST_ASSERT_TRUE(hil_plant_drop_cm() < 12.0f); /* the arm did not fall (Ch 3) */ }
The Monday jitter story has a fix that costs almost nothing: measure the loop time on the rig and gate on it. Say the control loop has a 1,000 µs deadline and the rig measures a worst case of 640 µs on the last good build. Set the gate at 800 µs, which is 80% of the deadline, so there is room for the unknown. The Friday change pushes the worst case to 910 µs. The deadline is still met, and nothing has failed in the field, yet the gate stops the merge. You learn about the loss of margin on Friday and not on Monday.
To measure on a rig, toggle a GPIO at the start and end of the loop and capture the pulse width with a timer input, or read the cycle counter (the Cortex-M DWT cycle counter on parts that have it) and report the maximum over a long run. Store the number per commit, so you see a trend, not only a threshold.
A test that fails at random teaches the team to ignore failures. Three habits keep a HIL suite honest. Reset the board and the plant model to a known state before each test. Use fixed seeds for any noise in the plant, so a failure repeats. And run each safety test on every rig now and then, to find a rig that is itself broken: a loose cable looks exactly like a firmware bug.
Finally, decide which tests block. A good split: host and SIL tests run on every push and must pass; the injection set runs on every merge request and blocks it; the long soak runs overnight and opens an issue. Whatever the split, record it, because the safety case will cite it.
On real hardware. Build a poor man’s HIL: a second board (an RP2040 or another Nucleo) plays the plant. It generates quadrature encoder pulses on two pins, reads the first board’s PWM, and can freeze the pulses on command over USB serial. A script on your laptop runs the test above, and a CI job calls it after each push. The measurement to repeat is the time from the freeze to the brake pin.
Chapter 7
Keep the numbers, the checklist and the state machine on one page, and find the sources behind each claim
Fail-safe firmware comes down to two lines. A fault must be seen in time, so detection time plus reaction time stays inside the fault tolerant time interval. The thing that sees it must be honest: a kick, a heartbeat or a check counts only if the real work must be alive for it to happen.
kick ← (every task checked in) AND (link fresh) · tdetect + treact ≤ FTTI
| Quantity | Value | Where it comes from |
|---|---|---|
| IWDG timeout | (RL + 1) × divider / 32 kHz; RL = 99 and /32 gives 100 ms | RM0383 (STM32F411), IWDG; LSI nominal, so a band in practice |
| IWDG keys | 0x5555 unlock, 0xCCCC start, 0xAAAA kick; 12-bit reload | RM0383, IWDG |
| WWDG reset | 7-bit counter; reset when 0x40 rolls to 0x3F or when kicked above W | RM0383, WWDG |
| WWDG window example | 36.7 to 49.9 ms (42 MHz APB1, WDGTB 3, W 0x50) | Worked in Chapter 0 from the RM0383 formula |
| Hang caught, kick in health task | 115 ms after the fault | The hero model: last kick 215 ms, timeout 100 ms |
| Heartbeat detection | worst case N × P; false alarms/h ≈ (3,600,000 / P) × (1 − p) × pN | Derived in Chapter 2; CANopen heartbeat frame is 0x700 + node ID |
| Linux spurious IRQ rule | disable a line when over 99,900 of 100,000 are unhandled | kernel/irq/spurious.c, note_interrupt() |
| ASIL by sum | S + E + C = 10 D, 9 C, 8 B, 7 A, below 7 QM | Consistent with the ISO 26262 summary on Wikipedia |
| SIL bands (per hour) | SIL 1 1e-6 to 1e-5; SIL 2 1e-7 to 1e-6; SIL 3 1e-8 to 1e-7; SIL 4 1e-9 to 1e-8 | IEC 61508 as summarised by TUV SUD and Wikipedia |
| Arm in Chapter 3 | I = 0.167 kg m²; hold torque 4.9 N m; 0.33 J at 2 rad/s; cut torque falls 50 cm | Toy model, computed in the page |
| MISRA C:2012 | 143 rules and 16 directives | Wikipedia, MISRA C |
c/* the safe-state machine: every fault maps to a reaction and a time budget */ typedef enum { ST_BOOT, ST_RUN, ST_STOPPING, ST_SAFE } state_t; typedef struct { uint32_t bit; uint16_t budget_ms; } fault_rule_t; static const fault_rule_t RULES[] = { { F_ENCODER, 60 }, { F_TASK_HANG, 115 }, { F_LINK_LOST, 150 }, }; static state_t st = ST_BOOT; static uint32_t t_first_fault; void safety_step(uint32_t faults, uint32_t now_ms) { switch (st) { case ST_BOOT: outputs_safe(); if (self_test_ok()) st = ST_RUN; break; /* safe output first */ case ST_RUN: if (faults) { t_first_fault = now_ms; begin_controlled_stop(); st = ST_STOPPING; } break; case ST_STOPPING: if (speed_zero() || now_ms - t_first_fault > BRAKE_AFTER_MS) { brake_close(); drive_sto(); st = ST_SAFE; } break; case ST_SAFE: /* latched: leave only by operator reset plus a passed self-test */ break; } if (st == ST_SAFE) log_reaction_ms(now_ms - t_first_fault); /* compare with RULES[].budget_ms */ }
The same watchdog set-up on Zephyr, adapted from the project’s own watchdog sample (Apache-2.0). It resets the SoC if you do not call wdt_feed() in time; feed it from your health task, never from a timer callback.
cstruct wdt_timeout_cfg cfg = { .flags = WDT_FLAG_RESET_SOC, /* reset the chip when it expires */ .window.min = 0, .window.max = 100, /* ms; min > 0 makes a window watchdog if the part supports it */ }; int ch = wdt_install_timeout(wdt, &cfg); wdt_setup(wdt, WDT_OPT_PAUSE_HALTED_BY_DBG); /* start; do not reset while a debugger halts the core */ /* in the health task, only when every check-in is fresh: */ wdt_feed(wdt, ch);
Not every item could be checked against a primary source. I did not open the text of IEC 60204-1 (the stop categories), ISO 26262 part 9 (decomposition) or the FTTI definition in part 1. They are written here as widely used summaries and marked as such. I also did not use any count of how many job postings ask for these skills, because I had no source to check it against. The STPA handbook was not opened either; the Leveson reference is to the book.
This lesson closes the firmware track’s safety thread. From the vector table to main shows the first instructions that must set the safe state. Interrupts and DMA explains the ISRs that Chapter 0 warned about. CAN and EtherCAT is the bus under Chapter 2. Motor control firmware does the controlled stop. The track continues with sleep and the battery budget and the bench and root cause. The planned Linux and real-time lessons cover the same ideas above the kernel: deadlines, the latency budget, and secure boot with updates (for the firmware side of updates see bootloaders and OTA).
Now press Present or Teach and explain, from memory, why a timer interrupt cannot guard a hung main loop and what a safe state is for a joint carrying a load. Then go back to the joint at the top, put the kick in the main loop, hang the sensor task, and say why nothing fires.