Try Embedded

Embedded C code patterns

Error handling, opaque handles, ring buffers, tables and other everyday shapes.

Shapes that recur in every codebase

Firmware written by different teams for different chips keeps arriving at the same few structures. Knowing them by name lets you read unfamiliar code quickly and answer design questions with something concrete. This guide covers the ones not given a guide of their own; ring buffers, bit manipulation and state machines are linked at the end.

Return a status, pass results by pointer

A function that can fail returns a status code; the useful result goes through an output parameter. The caller checks every status.

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

typedef enum { STATUS_OK = 0, STATUS_TIMEOUT, STATUS_RANGE, STATUS_BUSY } status_t;

static status_t adc_read_mv(uint8_t channel, uint16_t *out_mv) {
  if (channel > 15) return STATUS_RANGE;
  if (out_mv == NULL) return STATUS_RANGE;
  *out_mv = (uint16_t)(1650 + channel * 10);   // pretend conversion
  return STATUS_OK;
}

int main(void) {
  uint16_t mv;
  status_t s = adc_read_mv(3, &mv);
  if (s == STATUS_OK) printf("channel 3: %u mV\n", mv);
  s = adc_read_mv(20, &mv);
  if (s != STATUS_OK) printf("channel 20: error %d\n", s);
  return 0;
}

Conventions that make this work across a codebase:

  • 0 means success, so if (status) reads as "if it failed".
  • One shared status_t enum rather than every module inventing its own numbers.
  • Output parameters are never written on failure, so the caller cannot use stale data by accident.

Clean-up on failure with goto

C has no destructors, so a function that acquires several resources needs one place that releases them. A forward goto to a clean-up label is the accepted idiom (the Linux kernel uses it thousands of times):

status_t log_sample(void) {
  status_t s = STATUS_OK;
  if (!sensor_power_on())      return STATUS_BUSY;
  if ((s = spi_lock()) != STATUS_OK) goto power_off;
  if ((s = sensor_read(&raw)) != STATUS_OK) goto unlock;
  s = flash_append(&raw, sizeof raw);
unlock:
  spi_unlock();
power_off:
  sensor_power_off();
  return s;
}

Labels are in reverse order of acquisition, so each failure releases exactly what was taken.

Opaque handles

A header declares a type without its contents; only the .c file knows the layout. Users can hold a pointer but cannot reach inside.

/* uart.h */
typedef struct uart uart_t;                 /* incomplete type */
uart_t *uart_open(int instance, uint32_t baud);
int uart_write(uart_t *u, const void *data, size_t len);

/* uart.c */
struct uart {
  USART_TypeDef *regs;
  ring_t tx;
  uint32_t errors;
};
static struct uart instances[3];            /* static pool: no malloc */

This is encapsulation in C: the layout can change without recompiling users, and nobody can poke u->errors directly. Allocation comes from a static array of instances, not the heap.

Table-driven code

When behaviour depends on data, put the data in a const table rather than a long if chain. The table lives in flash and adding a case is one line.

#include <stdio.h>
#include <string.h>

typedef struct {
  const char *name;
  int (*handler)(int arg);
} command_t;

static int cmd_led(int on)   { printf("LED %s\n", on ? "on" : "off"); return 0; }
static int cmd_rate(int hz)  { printf("rate = %d Hz\n", hz); return 0; }
static int cmd_reset(int x)  { (void)x; printf("resetting\n"); return 0; }

static const command_t commands[] = {
  { "led",   cmd_led },
  { "rate",  cmd_rate },
  { "reset", cmd_reset },
};

static int dispatch(const char *name, int arg) {
  for (unsigned i = 0; i < sizeof commands / sizeof commands[0]; i++) {
    if (strcmp(commands[i].name, name) == 0) return commands[i].handler(arg);
  }
  printf("unknown command '%s'\n", name);
  return -1;
}

int main(void) {
  dispatch("led", 1);
  dispatch("rate", 200);
  dispatch("blink", 0);
  return 0;
}

The same shape appears as pin-mux tables, register initialisation lists ({ address, value } pairs written in a loop), and calibration curves.

Super loop with flags

Without an RTOS, most firmware is one loop that checks flags set by interrupts:

static volatile uint8_t events;
#define EV_UART_RX  (1u << 0)
#define EV_TICK     (1u << 1)

void SysTick_Handler(void) { events |= EV_TICK; }

int main(void) {
  init();
  for (;;) {
    uint8_t ev = take_events();      /* read and clear with interrupts off */
    if (ev & EV_UART_RX) handle_rx();
    if (ev & EV_TICK)    run_10ms_tasks();
    if (!ev) sleep_until_interrupt();
  }
}

Interrupts do the minimum (record that something happened); the loop does the work. Each handler must return quickly, because one slow handler delays all the others.

Assertions and defensive checks

  • assert() for things that can only be false if the code is wrong (a NULL pointer passed by our own module). In a release build it should log the file and line, then reset, not vanish.
  • Explicit checks for things that can legitimately go wrong (a sensor not responding, a corrupted packet).
  • _Static_assert for layout assumptions: structure sizes, buffer sizes that must be powers of two.

Pitfall: Never put an action inside assert(), such as assert(init_radio() == OK). If asserts are compiled out, the radio is never initialised.

Interview question: How do you achieve encapsulation in C?

Answer: With opaque types: the header declares typedef struct uart uart_t; and functions that take uart_t *, while the struct's fields are defined only in the .c file. Callers can hold and pass the handle but cannot access fields, so the implementation can change freely. Combine it with static for every internal function and variable, and allocate instances from a static array inside the module rather than the heap.

Interview question: What error-handling conventions would you set for a new firmware codebase?

Answer: One shared status enum with 0 as success; every fallible function returns it and is checked (with a compiler attribute such as warn_unused_result); results go through output pointers that are untouched on failure; a single clean-up path per function using goto labels; assert for programming errors, which in release logs the location and resets via the watchdog; and error counters per driver so field failures can be diagnosed.

Build it: let modules react to a new temperature

This is step 2 of the module project. When a new temperature arrives, the display must redraw, the heating control must decide, and the logger must record it. If the sensor module called all three directly, it would depend on every one of them. Instead they subscribe, and the sensor module only publishes.

Lab: Publish and subscribe with callbacks

Write a small publish/subscribe module with room for MAX_SUBSCRIBERS (4) callbacks. A callback has the type void (*)(int32_t centi, void *ctx): the new temperature in hundredths of a degree, and a context pointer given when subscribing (so one function can serve several objects).

  • sub_add(cb, ctx) registers a callback. It returns false if the table is full, or if this exact callback and context pair is already registered (subscribing twice must not deliver twice).
  • sub_remove(cb, ctx) unregisters that pair and returns true, or returns false if it was not registered.
  • publish(centi) calls every registered callback, in the order they subscribed, and returns how many it called. Removing a subscriber keeps the others in order.

Going deeper

Interview question: How would you structure an infusion pump's firmware so it can be certified?

Answer: Separate safety functions (rate control, occlusion and air detection, alarms) from the user interface and communications, with clear interfaces and no dynamic allocation. Use simple, analysable patterns (state machines, static tasks), make every requirement traceable to code and tests, and run static analysis to a coding standard. Independence between the controller and a safety monitor is often required.

Interview question: How would you report errors from deep inside a driver to the application without exceptions?

Answer: Return a status code from every fallible function and propagate it upwards, translating driver-specific codes into the module's own status type at each layer boundary so the application is not coupled to hardware details. Record extra context (which device, which operation, the raw hardware status) in an error counter or log rather than in the return value. Use warn_unused_result so callers cannot ignore it, and reserve asserts for programming errors.

Interview question: What is the difference between an assertion and error handling?

Answer: An assertion checks something that can only be false if the code itself is wrong, such as a NULL pointer passed by our own module or an impossible state, and its failure means a bug: log it and reset to a safe state. Error handling deals with conditions that can legitimately happen in correct code, such as a sensor not responding, a bad CRC or a full queue, and the program must recover from them. Mixing the two either hides bugs or crashes on recoverable events.

Explain it: In your own words, explain how opaque handles give encapsulation in C.

Answer: The public header declares a struct type without its contents, only typedef struct uart uart_t;, and functions that take a pointer to it. Code using the module can hold and pass the pointer but cannot see or touch the fields, because the full definition exists only inside the module's .c file. So the module's internals can change freely without breaking or even recompiling its users, the same effect as private members in C++. Instances usually come from a static array in the module rather than the heap.