Safety mechanisms
Defensive code, watchdog strategy, memory checks and redundancy.
Assume things will fail
Hardware fails randomly: bits flip from radiation, flash wears out, crystals stop, sensors drift, connectors corrode. Software fails systematically: every non-trivial program has bugs that some input will eventually trigger. A safe system does not assume either away. It detects faults, and reacts by reaching a safe state (motor off, valve closed, alarm raised) within a time the hazard allows.
The safety standards (IEC 61508, ISO 26262 and others) call these safety mechanisms and require evidence that they cover the relevant failure modes.
Defensive programming
Check what can be checked, cheaply, everywhere:
- Validate inputs at module boundaries: range, plausibility, rate of change. A temperature that jumps 80 °C in 10 ms is a sensor fault, not a fire.
- Check return values of every function that can fail, and define what happens on failure.
- Default cases: every
switchhas adefaultthat handles the impossible value (corrupted state variable) by going to a fault state. - Assertions for invariants that must hold if the code is correct, active in production with a defined reaction (log and reset to safe state).
- Redundant encoding of critical values: store a safety-critical variable together with its bitwise inverse, and check they match before use.
#include <stdio.h>
#include <stdint.h>
/* A safety-critical value stored twice: plain and inverted. A bit flip in either copy is detected. */
typedef struct { uint16_t value, inverse; } safe_u16_t;
static void safe_set(safe_u16_t *s, uint16_t v) { s->value = v; s->inverse = (uint16_t)~v; }
static int safe_get(const safe_u16_t *s, uint16_t *out) {
if ((uint16_t)~s->inverse != s->value) return -1; /* corruption detected */
*out = s->value;
return 0;
}
int main(void) {
safe_u16_t speed_limit;
uint16_t v;
safe_set(&speed_limit, 1200);
printf("read: %s\n", safe_get(&speed_limit, &v) == 0 ? "ok" : "CORRUPT");
speed_limit.value ^= 1u << 9; /* simulate a single-event upset */
if (safe_get(&speed_limit, &v) != 0) printf("read: CORRUPT -> enter safe state\n");
return 0;
}
Watchdog strategies
A watchdog is the basic detector for software that has stopped. Used well:
- An independent watchdog clocked separately from the CPU, so a clock failure is also caught.
- A windowed watchdog to catch code running too fast or skipping steps.
- Program flow monitoring: each critical function adds a checkpoint value to a signature; the watchdog is fed only if the accumulated signature matches the expected sequence for that cycle. This detects code that runs but in the wrong order.
- External watchdog ICs or a separate supervisory microcontroller for higher integrity levels, independent of the main MCU's failure modes.
Memory checks
| Check | Detects | When |
|---|---|---|
| Flash CRC over the application image | Corrupted code or constants | At start-up, and periodically in the background in small chunks |
| RAM test (March algorithms such as March C−) | Stuck bits, coupling faults | At start-up (destructive), and on small blocks at run time with save/restore |
| ECC RAM and flash (hardware) | Single-bit errors corrected, double-bit detected | Continuously; handle the error interrupts |
| Stack overflow detection | Stack growing into other data | MPU guard regions, stack canaries, watermark monitoring |
| MPU | Wild pointers, task isolation | Continuously |
IEC 60730 Annex H (household appliances, Class B) lists such tests explicitly, and MCU vendors ship certified self-test libraries (for example STM32 Class B / SIL libraries) implementing them.
CPU and peripheral checks
- CPU register and instruction self-tests (core self-test libraries).
- Clock monitoring: compare the main clock against an independent oscillator (clock security system, or measure one clock with a timer on another).
- ADC checks: convert known references (internal reference, ground) and verify the results; read critical analog inputs on two channels.
- Output read-back: after driving an output, read its actual state back (through a feedback input) to detect a stuck or shorted driver.
- Communication protection: CRC, sequence counters (detect lost or repeated messages), timeouts (detect a silent sender), and source identifiers, as specified by profiles such as AUTOSAR E2E.
Redundancy
When a single channel cannot achieve the required integrity:
| Architecture | Meaning | Property |
|---|---|---|
| 1oo1 | One channel | No fault tolerance; diagnostics must reach a safe state |
| 1oo2 | Two channels; either can trip to safe state | High safety (a fault in one does not prevent tripping), more spurious trips |
| 2oo2 | Both must agree to trip | Fewer spurious trips, lower safety |
| 2oo3 | Majority vote of three | Both safe and available; tolerates one fault |
Lockstep cores (Cortex-R5, Cortex-M7 lockstep variants, Infineon AURIX, TI Hercules) run two cores executing the same instructions, with hardware comparing their outputs every cycle; any difference raises a fault. Diversity (different algorithms, different sensors, different teams) protects against common-cause failures that identical redundancy cannot catch.
The safe state and fault reaction
Every detected fault needs a defined reaction, decided during hazard analysis:
- Detect within the diagnostic test interval.
- React within the fault reaction time so the total stays within the fault-tolerant time interval of the hazard.
- Reach and hold the safe state, which must itself be safe on loss of power (de-energise to trip).
- Log the fault with enough context for analysis.
- Recover only when it is safe to do so, sometimes only after human intervention.
Pitfall: A watchdog reset that brings the system back up in exactly the same state can loop forever, or briefly re-energise an actuator on each restart. Count resets and stay in the safe state after repeated faults.
Interview question: What safety mechanisms would you put in the firmware of a motor controller?
Answer: An independent windowed watchdog with program-flow monitoring; start-up and periodic background CRC of flash and March tests of RAM, or ECC handling; stack overflow detection with the MPU; clock monitoring; plausibility checks on current, position and speed sensors with redundant or diverse measurements; ADC reference checks; output read-back of the gate drivers and the use of the timer's hardware break input to cut PWM within microseconds on overcurrent; CRC, counters and timeouts on command messages; and a defined de-energised safe state reached within the fault-tolerant time, with fault logging and limited restarts.
Interview question: Compare 1oo2 and 2oo3 architectures.
Answer: In 1oo2, two channels each monitor the system and either one can command the safe state, so one failed channel cannot stop a necessary shutdown, giving high safety, but any single faulty channel can cause a spurious trip, reducing availability. In 2oo3, three channels vote and the majority decides, so the system tolerates one faulty channel both ways, keeping it safe and available, at the cost of a third channel and the voting logic. The choice depends on whether unwanted trips are only a nuisance or are themselves hazardous.
Build it: a switch that cannot lie about the brake
This is step 2 of the module project, the electronic parking brake. The highest-rated hazard is the brake changing state when nobody asked, so the button in the cabin has two contacts that move together but are wired opposite ways: channel A reads 1 when the button is pulled, channel B reads 0. A broken wire, a short or a stuck contact makes the two disagree, and the software must notice, and then do the safe thing: hold the brake as it is.
Lab: Two channels, plausibility and a safe state
epb_step(e, a, b, pedal) runs every 10 ms with the two channels and whether the brake pedal is pressed. It updates e->applied, and latches e->fault.
- A=1, B=0 means apply; A=0, B=1 means release; anything else means the channels disagree.
- Disagreement for 3 samples in a row latches
fault. From then on nothing changes: the brake stays as it is and the button is ignored, until the ECU restarts. Fewer than 3 (contact bounce, a moment's interference) changes nothing, and resets the count once the channels agree again. - A request takes effect only when the same valid request is seen on 2 samples in a row, counting from the first sample after it changed.
- Apply is always obeyed. Release is obeyed only while the brake pedal is pressed, as the regulations require; otherwise it is ignored (and must be asked again with the pedal pressed).
Going deeper
Interview question: How would you design a brake-by-wire unit to reach a safe state on any fault?
Answer: Identify hazards and the safe state for each (often reverting to a mechanical backup or a reduced mode), then add detection: redundant sensors compared against each other, memory and CPU self-tests, program-flow and watchdog monitoring, and plausibility checks. Make detection and reaction faster than the fault-tolerant time interval, and independent of the function it protects.
Interview question: What is a safe state, and why must it hold without power?
Answer: The condition the system enters when a fault is detected so that no harm results: a motor de-energised, a valve closed, a heater off, an alarm raised. Many faults include losing power or the controller resetting, so the safe state must be the de-energised default of the hardware (de-energise to trip), not something firmware must actively maintain.
Interview question: What is program flow monitoring?
Answer: A technique where critical functions update a running signature or checkpoint sequence as they execute, and a monitor, often the code that feeds the watchdog, checks the signature matches the expected sequence for each cycle. It detects code that runs but in the wrong order or skips steps, which a simple watchdog that is fed regularly cannot detect.
Explain it: In your own words, explain why safety-related firmware uses periodic RAM and flash tests.
Answer: Hardware can fail while the product is running: a bit in RAM can flip because of radiation or a defect, and flash contents can degrade. If firmware then uses a corrupted value or instruction, it could command something dangerous without any obvious error. Checking a CRC of the flash image and running tests on RAM at start-up and in small pieces during operation detects such corruption within a known time, so the system can enter its safe state before a hidden hardware fault turns into a hazard. Hardware ECC, where available, does this continuously.