Try Embedded

Error handling and fault strategy

Error codes, assertions, safe states and keeping evidence of what went wrong.

Errors are part of the design

On a desktop, an error can print a message and exit. Firmware cannot exit: it controls something physical, often with nobody watching. So error handling in firmware is a design decision made up front: what can fail, how will we know, and what state is safe?

Three kinds of problem need different answers:

KindExampleAnswer
Expected failureA sensor does not answer, a checksum is wrong, a queue is fullReturn an error code; the caller retries, uses a default, or reports it
Programming errorA NULL pointer passed in, an index out of range, an impossible stateassert: stop in development, fail safe in the field
Hardware or system faultHardFault, brown-out, watchdog timeout, stack overflowFault handler: record what happened, go to a safe state, reset

Return codes

C has no exceptions, so functions that can fail return a status, and give their result through a pointer:

#include <stdio.h>
#include <stdint.h>

typedef enum {
  ERR_OK = 0,
  ERR_TIMEOUT,      /* the device did not answer */
  ERR_CRC,          /* it answered, but the data was corrupted */
  ERR_RANGE,        /* the value cannot be right */
} err_t;

static const char *err_name(err_t e) {
  static const char *names[] = { "OK", "TIMEOUT", "CRC", "RANGE" };
  return names[e];
}

/* Pretend driver: the "attempt" decides what happens, as a flaky bus would. */
static err_t sensor_read(int attempt, int16_t *celsius) {
  if (attempt == 0) return ERR_TIMEOUT;
  if (attempt == 1) return ERR_CRC;
  *celsius = 23;
  return ERR_OK;
}

/* The caller decides the policy: retry a few times, then fall back. */
static int16_t read_with_retry(void) {
  int16_t value;
  for (int attempt = 0; attempt < 3; attempt++) {
    err_t e = sensor_read(attempt, &value);
    printf("attempt %d: %s\n", attempt, err_name(e));
    if (e == ERR_OK) return value;
  }
  return INT16_MIN;   /* a value the rest of the code treats as "unknown" */
}

int main(void) {
  printf("temperature: %d C\n", read_with_retry());
  return 0;
}

Rules that keep this manageable:

  • One error type for a module (or the project), with names that say what happened, not where.
  • Never ignore a returned error. Compilers can enforce it: GCC's __attribute__((warn_unused_result)), or C23's [[nodiscard]].
  • Decide the policy at the right level. A driver reports ERR_TIMEOUT; the application decides to retry, use the last good value, or raise an alarm.
  • Do not overwrite the output on failure, so callers can keep the last good value.

Assertions

An assertion states something that must be true if the code is correct. Failing one means a bug, not a bad input from the outside world.

void motor_set_speed(motor_t *m, int16_t rpm) {
  ASSERT(m != NULL);                     /* a caller passing NULL is a bug */
  ASSERT(rpm >= -MAX_RPM && rpm <= MAX_RPM);
  ...
}

In firmware, define your own ASSERT rather than using <assert.h>, whose failure path prints and calls abort():

#define ASSERT(cond) do { if (!(cond)) assert_failed(__FILE__, __LINE__); } while (0)

void assert_failed(const char *file, int line) {
  disable_outputs();             /* motors off, heaters off: the safe state */
  log_fault(FAULT_ASSERT, file, line);
  __BKPT(0);                     /* stops here if a debugger is attached */
  NVIC_SystemReset();            /* in the field: reset and report on the next boot */
}

Use static_assert (C11 _Static_assert) for things that can be checked at compile time, such as a struct's size matching a protocol or a buffer size being a power of two. Those cost nothing at run time.

Safe states

For every output, decide in advance what "safe" means: a heater off, a valve closed, a motor stopped with its brake on, a door unlocked (or locked, depending on the risk). The error path must reach it without relying on the part that failed: it should not need the RTOS, the heap, or the driver that just crashed.

Hardware helps: outputs with pull resistors that are safe when the pin floats (as it does during reset), and a watchdog that resets the system if the software stops responding.

Keeping evidence

A device in the field that resets "sometimes" is impossible to fix without evidence. Keep a small fault record in RAM that survives a reset (a .noinit section) or in flash:

  • what happened (an error code, the assert's file and line, the fault registers),
  • when (uptime, or a real-time clock),
  • how often (counters for each kind of fault and reset cause).

Report it on the next boot and in diagnostics. Counting resets by cause (power-on, brown-out, watchdog, software) is cheap and often the first clue.

Pitfall: Resetting on every error hides the problem. A device that silently reboots every few minutes looks like it works in a quick test. Count the resets and report them.

Interview question: How do you handle errors in firmware with no exceptions and no operating system?

Answer: I separate expected failures from bugs. Expected failures, like a sensor timeout or a bad checksum, are returned as error codes from an enum, and the caller decides the policy: retry, use the last good value, or report. Callers must check them, which the compiler can enforce with warn_unused_result. Programming errors are caught with assertions, which halt under the debugger and in the field drive the outputs to a safe state, record the location and reset. Hardware faults go to fault handlers that save the fault registers to no-init RAM. Every reset cause is counted and reported, and a watchdog covers software that stops responding.

Build it: keep the house safe when the sensor fails

This is step 4, the last of the module project. One day the sensor's cable works loose. A thermostat that keeps heating on its last reading can cook a house; one that stops at the first glitch annoys everyone. The rule: retry briefly, then fall back to a safe mode, and come back by itself when the sensor recovers.

Lab: Retries, safe mode and recovery

sensor_read(&t) is provided by the bench: it returns 0 and a temperature, or a negative error code. Write control_step(target), run once a second, which returns what it decided:

  1. Try sensor_read up to 3 times in this step. On the first success, use that reading.
  2. If all 3 attempts fail, that step has failed. After 3 failed steps in a row, enter safe mode: the heater is forced off and the step returns ACTION_SAFE. Before that, a failed step keeps the heater as it was and returns ACTION_HOLD.
  3. With a good reading: if in safe mode, stay there until 2 good steps in a row have been seen (one good reading may be a fluke), still returning ACTION_SAFE. Otherwise run simple control (heater on below the target, off at or above it) and return ACTION_HEAT_ON or ACTION_HEAT_OFF.

Also keep the most recent error code: last_error() returns it (0 if there has never been one). The service menu shows it.

Going deeper

Interview question: How would you design a greenhouse controller's fault handling for months without supervision?

Answer: Classify faults by what the system can still do: a dry tank stops the pump and latches until someone refills it; a broken sensor falls back to a safe schedule; a hang is caught by the watchdog, which restarts into a safe state. Log every fault with a time and reason in non-volatile memory, report it, and never let one failure silently disable a safety function.

Interview question: What should happen in an assert handler in production firmware?

Answer: It must not depend on the part of the system that may be broken: no heap, no RTOS calls, ideally no complex drivers. It first puts the outputs into their defined safe state, then records the evidence (file and line or a code, plus registers if useful) in RAM that survives reset or in flash, then resets the device, or stays in a safe stopped state if restarting is dangerous. If a debugger is attached it can trigger a breakpoint instead. Disabling asserts in release builds is risky, since the checks then stop protecting the field.

Interview question: Why count resets by cause?

Answer: Because a reset hides what went before it. Most microcontrollers have a reset-cause register that tells power-on, brown-out, watchdog, software reset and external pin apart. Counting each kind, and storing the count across resets, shows patterns that a single test never would: brown-outs point at the power supply, watchdog resets at a hang, software resets at asserts or fault handlers. It is cheap and is often the first evidence available from the field.

Explain it: In your own words, explain the difference between returning an error code and asserting, and when to use each.

Answer: An error code reports something that can legitimately go wrong while the code is correct, such as a sensor not answering or bad data arriving, and lets the caller decide what to do about it. An assertion checks something that can only be false if the program itself has a bug, such as a forbidden NULL argument or an impossible state. Error codes are handled and the program carries on; a failed assertion means the program can no longer be trusted, so it stops in development and moves to a safe state and records the evidence in the field.