Embedded firmware design and development
Practical, exam-focused notes on designing and developing embedded firmware: definitions, design flow, memory/linker/startup, interrupts/ISRs, concurrency and synchronization, drivers, bootloaders, testing and debugging, with formulas and worked examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Firmware is the low-level software that makes embedded hardware work. Engineers use firmware to bring up boards, control peripherals, meet timing and safety requirements, and enable higher-level software such as an RTOS or applications (see RTOS basics: tasks, processes and threads).
Key ideas
(Definitions are bolded the first time they appear.)
Firmware — the software that runs on an embedded processor to control hardware directly. Assumption: firmware typically runs without a general-purpose OS, or under a small RTOS. Usefulness: it implements device drivers, startup code, control loops and communication stacks.
Bootloader — a small program that runs after reset to initialise hardware and load or start the main firmware image. Typical tasks: configure clocks, set up minimal RAM (its own stack), initialise peripherals needed for loading, verify image integrity (CRC or signature) and jump to the application entry; the application's startup code then copies .data and clears .bss.
Startup code (reset handler) — code that executes on reset before main(); it establishes the initial stack pointer (typically loaded by hardware from the first vector entry), copies initialized data from non-volatile memory to RAM, clears uninitialized data, and calls constructors if the language requires. Assume presence of a vector/interrupt table pointing to handlers.
Vector table — an ordered list of pointers (addresses) placed at a known memory address (often address 0x00000000 or at an implementation-defined exception vector base). Each entry corresponds to an exception or interrupt. When asked for a diagram, draw a vertical list: at left the addresses (e.g. 0x00000000, 0x00000004, ...), at right the label (.stack_top, Reset_Handler, NMI_Handler, HardFault_Handler, IRQ0_Handler ...). Label the table base and show that on reset hardware loads the initial stack pointer from entry 0 and the PC from the Reset entry (entry 1).
Linker script / memory map — a text file for the linker that defines memory regions (FLASH, RAM) and places sections (.text, .data, .bss, .isr_vector, .heap, .stack) into those regions. Exact statement: the linker assigns addresses (load/run addresses) to sections according to MEMORY and SECTIONS directives; without correct mapping code may end up in RAM that is not initialised.
Device driver — software that controls and provides an abstract interface to a hardware peripheral. Distinguish HAL (Hardware Abstraction Layer) — a thin, portable layer exposing peripheral functions — from BSP (Board Support Package) — board-specific initialisation and mapping.
Interrupt — an asynchronous hardware event that makes the processor suspend normal execution and jump to an ISR (Interrupt Service Routine). Exact behaviour: on interrupt, the processor saves minimal state (stack pointer, some registers or program counter depending on architecture), switches context if needed, and sets an interrupt-in-progress flag. Assumption: interrupt latency includes hardware propagation, vectoring, and prologue code.
ISR (Interrupt Service Routine) — the function that handles an interrupt. Requirements: keep ISRs short, avoid blocking calls, use volatile for shared data, and signal tasks if heavy processing is needed.
DMA (Direct Memory Access) — a hardware controller that moves data between peripherals and memory without the CPU executing the load/store instructions. Use DMA to reduce CPU load for high-throughput tasks (e.g., ADC sampling, UART DMA). Assume peripheral and DMA controller require correct configuration and memory alignment; on systems with data caches/MMU, ensure cache maintenance or use coherent/uncached buffers to avoid stale or dirty data.
Volatile — a qualifier in C telling the compiler that the value of a variable may change at any time (for example by hardware or ISR) so it must not optimize away repeated reads/writes. Exact statement: each evaluation of a volatile object is a volatile access that must result in an actual memory read/write; the compiler must not elide or reorder volatile accesses relative to each other. Note: volatile is not a substitute for atomicity or inter-thread memory ordering.
Atomic operation — an operation that completes without interruption; intermediate states are not visible. Example: single-word write may be atomic on many 32-bit architectures if aligned. Exact claim: only operations guaranteed atomic by the architecture should be assumed atomic.
Critical section — a section of code that must execute without concurrency interference. Methods to protect: disable interrupts (on single-core), use mutexes/semaphores (with an RTOS), or use atomic instructions (e.g. compare-and-swap) if supported.
Race condition — incorrect behaviour caused by unsynchronised concurrent access to shared data. Common exam derivation: show two tasks reading and writing a shared counter — final value depends on interleaving.
Reentrancy — a function is reentrant if it can be interrupted and safely called again (by interrupt or another thread) before its previous invocation completes. Requirement: avoid static/ global modifiable data without protection.
Memory mapped I/O — peripheral registers appear at specific addresses in the processor address space. Exact note: reading/writing these addresses causes hardware side effects.
Watchdog timer — hardware timer that resets the system if not periodically serviced; used for fault recovery. Behaviour: if watchdog not refreshed before timeout, hardware resets processor.
Link-time and run-time constraints — firmware must meet size limits, startup time, RAM usage and worst-case execution time (WCET) requirements. Assume you will compute timing against CPU clock and instruction cycle counts.
Design flow (concise): requirements → hardware bring-up (BSP, bootloader, startup) → drivers and HAL → core application and RTOS integration → testing (unit, integration) → system testing and field updates. Use version control and CI.
Formulas
T_exec = N_cycles / f_clk — execution time. N_cycles = number of CPU cycles consumed by code; f_clk = CPU clock frequency (Hz). SI units: seconds (s).
throughput = bits_transferred / T_total — for communication channels. Units: bits per second (bps).
CPU_util (%) = (T_exec_task / T_period_task) * 100 — CPU utilisation for periodic tasks. T_exec_task and T_period_task in seconds.
bus_util = (transfer_time_per_transaction * transactions_per_second) — fraction (0..1) of bus busy time.
Remember C syntax snippets to remember in firmware:
volatile uint32_t *REG = (volatile uint32_t *)0x40000000;— map registervoid MyISR(void)— ISR handler; mapping to the vector is toolchain/architecture-specific (e.g., CMSIS on ARM Cortex-M: the handler name must match the vector; some MCUs use attributes like__attribute__((interrupt(<VECTOR>)))).__disable_irq(); __enable_irq();— disable/enable interrupts (CMSIS names)memcpy(dest, src, size);— can be used in startup to copy .data if the C runtime is available; otherwise use a simple word copy loop- Linker script: MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K } SECTIONS { .text : { *(.text) } > FLASH }
Worked examples
- Execution time of an ISR and CPU utilisation Problem: An ISR takes 360 cycles on a 120 MHz CPU. The interrupt fires at 1 kHz. Compute ISR execution time and CPU utilisation due to ISR. Steps:
- Formula:
T_exec = N_cycles / f_clk. T_exec = 360 cycles / 120e6 Hz = 3.0e-6 s = 3.0 µs.- Interrupt rate period = 1/1000 s = 1 ms = 0.001 s.
- CPU utilisation =
(3.0e-6 / 0.001) * 100 = 0.3 %. Answer: ISR takes 3.0 µs; CPU utilisation 0.3%.
- Startup: placing .text in Flash and .data in RAM with linker symbols and steps Problem: Explain the steps and code to initialise .data and .bss at startup when .text is in Flash at address 0x08000000 and RAM starts at 0x20000000. Model answer (diagram + code):
- Draw memory: at left FLASH region starting 0x08000000, label .vector_table at 0x08000000, .text after that; draw RAM box at 0x20000000 with .data and .bss.
- Linker provides symbols: _sidata (start of initialised data values in flash), _sdata (start of .data in RAM), _edata (end of .data), _sbss, _ebss, _stack_top.
- Reset handler pseudo-code (numbered steps):
- Set MSP (main stack pointer) = _stack_top.
- Copy .data: for (p = _sdata, q = _sidata; p < _edata; ) { *p++ = *q++; }
- Clear .bss: for p = _sbss; p < _ebss; ++p) *p = 0;
- Call SystemInit() to configure clocks if needed.
- Call main().
- Explain: this copies initialized global variables to RAM and zeros uninitialized globals.
- Race condition with two tasks incrementing a shared counter (trace)
Problem: Two tasks A and B run on single-core with interrupts disabled in critical sections only for one task. Shared variable:
uint32_t counter = 0;Each task executescounter = counter + 1;once. Show how final counter may be 1. Trace (assume non-atomic read-modify-write compiled into load, increment, store):
- Task A: LOAD counter → obtains 0 in register r1.
- Task A: preempted before STORE.
- Task B: LOAD counter → obtains 0 in r2.
- Task B: INC r2 → r2 = 1.
- Task B: STORE counter = 1.
- Task A resumes: INC r1 → r1 = 1.
- Task A: STORE counter = 1 (overwrites 1). Final value = 1 not 2. Correct solution: protect increment with critical section (disable interrupts or mutex) or use atomic instruction.
Common mistakes
- Placing the vector table at wrong address or not aligning it — hardware cannot vector and system will hard-fault. Always follow the MCU manual's required alignment.
- Using blocking calls inside ISRs (e.g., sleep, malloc, semaphore waits) — can deadlock and increase latency.
- Assuming all unaligned accesses are atomic — many architectures require alignment for atomicity.
- Not accounting for interrupt latency when computing worst-case response times and missed deadlines.
- Leaving debug artifacts (e.g., busy-wait loops, large logging) enabled in production build.
- Relying only on printf for debugging time-critical code without considering its blocking or heavy I/O cost.
For your exam
Kinds of questions you will see:
- Definitions and short notes: define firmware, bootloader, ISR, HAL, DMA, volatile and atomic. Full-marks answer: give the definition, a one-line purpose/use case, and one caveat (e.g., volatile vs atomic).
- Diagrams: draw the vector table, memory map (FLASH/RAM with section placement), or startup flow. Full answer: labelled addresses, section names, and arrows showing copy from FLASH to RAM for .data.
- Derivations: compute execution time given cycles and clock, or CPU utilisation for periodic interrupts/tasks. Show formula and units.
- Short programs/traces: show interleavings causing race conditions and propose fixes (disable IRQs, mutex, atomic ops). Full answer: provide the trace showing lost update and code for fix.
- Linker/startup configuration: explain linker symbols and what startup must do. Full answer: list necessary symbols and exact startup steps.
- Testing/debugging: give procedures for unit testing drivers, integration, use of JTAG/SWD, assert/fault handlers, and CRC-based image verification. Full answer: include tools and what to check at each stage.
Quick check
- What is firmware? 2. Formula for execution time from cycles and clock? 3. What does the C
volatilequalifier guarantee? Answers: 1) Software that runs on an embedded processor to directly control hardware, initialises board and runs application code. 2)T_exec = N_cycles / f_clk(seconds). 3)volatileguarantees that each evaluation of the object is an actual memory access and that such accesses are not elided or reordered relative to other volatile accesses; it does not guarantee atomicity or inter-thread memory ordering.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?