Firmware Programming

Embedded Firmware Development: Core Programming Concepts

Learn the core concepts of embedded firmware development: memory layout, startup code, registers, interrupts, volatile, state machines, toolchains and testing.

On this page
  1. What embedded firmware development involves
  2. Execution models: bare metal, RTOS and embedded Linux
  3. Memory: flash, RAM and how a firmware image is laid out
  4. From reset to main(): the startup sequence
  5. Talking to hardware: registers, peripherals and HALs
  6. Interrupts and concurrency
  7. Structuring firmware: superloops, state machines and tasks
  8. Timing and power
  9. Languages for embedded development
  10. The toolchain: build, flash and debug
  11. Testing firmware
  12. A practical development workflow
  13. Common questions
  14. Where to go next

Embedded firmware development means writing the software that runs directly on a device’s microcontroller or processor. It’s the code that reads a sensor, drives a motor, refreshes a display or talks to a radio. The basic skills overlap with ordinary programming, but the environment is different. Memory is measured in kilobytes, there may be no operating system, timing can matter down to the microsecond, and a bug can leave a physical device stuck in the field.

This guide covers the core concepts that show up in almost every firmware project. For each topic, it links to a more detailed article in this section.

What embedded firmware development involves

Firmware vs. embedded software vs. embedded system

The terms overlap, and people use them loosely:

  • An embedded system is the whole product: hardware plus software built for a dedicated job. A thermostat, a car’s engine control unit or a USB keyboard are all examples.
  • Embedded software is any software running on that system. It can include an operating system, middleware such as a Bluetooth or TCP/IP stack, and the application.
  • Firmware usually means the low-level, hardware-specific software stored in non-volatile memory (typically flash) that starts running at power-on. On small microcontrollers, the firmware is all the software.

For a plain-language definition with examples, see What is an embedded program?

What makes it different from desktop or web programming

A few constraints shape nearly every decision:

  • Limited resources. A common microcontroller might have somewhere between a few KB and a few MB of flash, and even less RAM. You can’t assume memory is available.
  • Direct hardware access. You configure clocks, pins and peripherals yourself, often by writing to specific memory addresses.
  • Real-time requirements. Many systems must respond to events within a bounded time, not just “eventually.”
  • Long, unattended operation. Devices may run for years without a restart. Small leaks or rare race conditions eventually surface.
  • Cross-development. You write and compile code on a PC (the host) and run it on different hardware (the target). That changes how you build, load and debug.

Execution models: bare metal, RTOS and embedded Linux

Firmware generally runs in one of three ways:

Model What it is Typical use
Bare metal Your code runs directly on the CPU with no OS. Usually a main loop plus interrupt handlers. Small MCUs, simple or very timing-sensitive devices
RTOS A small real-time kernel (for example FreeRTOS or Zephyr) schedules multiple tasks by priority Devices juggling several concurrent activities, such as networking plus sensing plus UI
Embedded Linux A full OS on a more powerful processor with an MMU Gateways, cameras, devices with rich UIs or complex networking

There’s no universally right choice. Bare metal is easy to reason about and has almost no overhead, but it gets harder to manage as features pile up. An RTOS adds structure and priority-based scheduling at the cost of some RAM, flash and new concurrency hazards. Embedded Linux gives you drivers, filesystems and networking out of the box, but needs far more hardware and boots more slowly.

Memory: flash, RAM and how a firmware image is laid out

Sections: .text, .rodata, .data, .bss, stack and heap

A compiled firmware image is split into sections, which the linker places in specific memory regions:

  • .text: machine code. Lives in flash.
  • .rodata: constants, string literals and lookup tables. Usually stays in flash, which is why marking tables const can save RAM.
  • .data: initialized global and static variables. Their initial values are stored in flash and copied into RAM at startup.
  • .bss: zero-initialized globals and statics. They take up RAM, and startup code clears them to zero.
  • Stack: function call frames, local variables and saved registers during interrupts. Lives in RAM.
  • Heap: memory for malloc(), if your project uses it at all.

The linker script and map file

On a PC, the OS decides where your program lives. On a microcontroller, a linker script tells the linker where flash and RAM start, how big they are, and where each section goes. Vendor tools usually generate one for you, but it helps to be able to read it.

After each build, the linker can produce a map file listing every symbol, its address and its size. When you run out of flash or RAM, the map file is the first place to look.

Why most firmware avoids dynamic allocation

Many embedded projects avoid malloc() and free() entirely, or allow them only during initialization. Repeated allocation can fragment a small heap until an allocation fails, possibly weeks after deployment. Allocation time can also be unpredictable. Coding guidelines such as MISRA C restrict dynamic memory for these reasons. The common alternative is static allocation: fixed-size buffers, pools and queues sized at compile time.

From reset to main(): the startup sequence

On a microcontroller, main() isn’t the first thing that runs. After reset, roughly the following happens (details vary by architecture):

  1. The CPU fetches the initial stack pointer and the reset handler’s address from the vector table. On Arm Cortex-M, both sit at the start of the vector table.
  2. The reset handler, usually written in assembly or minimal C, sets up anything needed before C code can run.
  3. It copies the .data section’s initial values from flash to RAM.
  4. It zeroes the .bss section.
  5. It often calls a system initialization function to configure clocks.
  6. It calls main().

Firmware main() normally never returns. It contains an infinite loop. This startup code is one of the few places where hand-written assembly is still common; see assembly language programming for embedded systems.

Talking to hardware: registers, peripherals and HALs

Memory-mapped registers and bit manipulation

Peripherals such as GPIO, timers, UARTs and ADCs are controlled through registers that appear at fixed memory addresses. Writing to a register might switch a pin high. Reading another might tell you whether a byte has arrived.

In C, you access registers through pointers to volatile integers, or through structs that overlay a peripheral’s register block. Because each bit often has its own meaning, firmware relies heavily on bitwise operators:

GPIOA->ODR |=  (1U << 5);   /* set bit 5: drive pin PA5 high */
GPIOA->ODR &= ~(1U << 5);   /* clear bit 5: drive PA5 low */
GPIOA->ODR ^=  (1U << 5);   /* toggle PA5 */

The detailed patterns, including multi-bit fields and write-1-to-clear registers, are in bit manipulation in embedded C.

Vendor HALs, CMSIS and drivers

Few teams write every register access by hand. Chip vendors provide hardware abstraction layers (HALs) and drivers, and Arm provides CMSIS, a standard set of headers and core functions for Cortex-M devices. A typical firmware stack looks like this:

  • Application logic
  • Middleware (USB, file system, network stack, GUI library)
  • Board support / drivers
  • HAL or register definitions
  • Hardware

HALs make code faster to write and somewhat more portable. Direct register access gives tighter control and smaller code. Many projects mix both.

Interrupts and concurrency

Interrupt service routines

An interrupt lets hardware pause the main program to handle an event right away: a timer expiring, a byte arriving on a UART, a button press. The function that runs is the interrupt service routine (ISR). Good ISRs are short. They acknowledge the hardware, grab or store the minimum data, set a flag, and return. The heavy work happens later in the main loop or a task. The step-by-step guide is how to write an interrupt service routine in C.

Shared data, volatile and critical sections

As soon as an ISR and the main loop share a variable, two problems appear:

  1. Compiler optimization. The compiler may assume a variable can’t change unexpectedly, and keep it cached in a register. Declaring it volatile forces every access to go to memory. See the volatile keyword in embedded C.
  2. Atomicity. volatile doesn’t make an operation atomic. If the main loop reads a 32-bit counter on an 8-bit CPU, an interrupt can fire halfway through the read. Protect multi-step accesses with a critical section, which means briefly disabling interrupts, or with atomic instructions where the hardware provides them.

These same hazards appear between RTOS tasks. There you also have mutexes, semaphores and queues.

Structuring firmware: superloops, state machines and tasks

Small bare-metal firmware often uses a superloop:

int main(void)
{
    system_init();
    for (;;) {
        read_inputs();
        update_logic();
        write_outputs();
    }
}

The key rule is that nothing in the loop should block for long. If update_logic() sits in a busy-wait delay, everything else stalls. Finite state machines solve much of this. Each function call does a small amount of work based on the current state, then returns, so many activities can share one loop without blocking each other. See how to implement a state machine in embedded C.

When there are many independent activities with different deadlines, an RTOS lets you write each one as a separate task with its own priority.

Timing and power

Most firmware needs a sense of time. Usually that comes from a hardware timer generating a periodic “tick” interrupt, such as SysTick on Cortex-M. Code can then use non-blocking timeouts (“has 500 ms passed since X?”) instead of busy-wait delays.

Power matters for anything battery-operated. Common techniques include:

  • Putting the CPU into a sleep mode whenever there’s nothing to do, and waking on interrupts.
  • Turning off peripheral clocks you aren’t using.
  • Running at a lower clock speed where performance allows.
  • Batching work so the device wakes less often.

Measuring actual current draw, rather than estimating it, is usually the only reliable way to know whether these techniques are working.

Languages for embedded development

  • C is still the most widely used language for microcontroller firmware. Compilers exist for nearly every chip, and the language maps closely to the hardware. See Embedded C programming for microcontrollers.
  • C++ is common in larger firmware projects. Teams often use a restricted subset, for example avoiding exceptions and heap allocation on small targets.
  • Assembly is still used for startup code, context switching, and occasional hand-optimized routines.
  • Rust is getting more attention for its memory-safety guarantees and has growing embedded support.
  • MicroPython/CircuitPython are popular for prototyping and education on more capable boards.
  • Go (via TinyGo) and functional languages occupy smaller niches. See Go and functional programming for embedded systems.

The toolchain: build, flash and debug

A typical setup includes:

  • A cross-compiler such as the Arm GNU Toolchain (arm-none-eabi-gcc), avr-gcc, LLVM/Clang, or a commercial compiler like IAR or Arm Compiler.
  • A build system such as Make or CMake, often hidden behind an IDE.
  • An IDE or editor: vendor IDEs like STM32CubeIDE or MPLAB X, or VS Code with extensions. Compare options in embedded development tools: IDEs, toolchains and simulators.
  • A debug probe connected over JTAG or SWD. It lets you flash the chip, set breakpoints and inspect memory while the code runs on real hardware. See debugging microcontrollers with JTAG, SWD and GDB.

Simulators and emulators can help before hardware is ready. Tools range from circuit-plus-MCU simulators such as Proteus to instruction-level emulators like QEMU and Renode. For an overview by use case, see which software is best for simulation.

Testing firmware

Firmware testing usually happens at several levels:

  • Unit tests on the host. Hardware-independent logic such as parsers, filters and state machines can be compiled for your PC and tested with frameworks like Unity or GoogleTest. This works best when hardware access sits behind a thin interface you can replace with a fake.
  • On-target tests. The same or additional tests run on the real microcontroller to catch compiler, alignment and timing differences.
  • Hardware-in-the-loop (HIL). Automated rigs drive the device’s inputs and check its outputs.
  • Static analysis. Tools that flag undefined behavior, MISRA violations and common bugs without running the code.

Designing for testability early, by keeping logic separate from register access, makes all of these much easier.

A practical development workflow

A reasonable path for a new firmware project looks like this:

  1. Get a “blinky” running on the target. This proves the toolchain, flashing and clock setup all work.
  2. Bring up one peripheral at a time and confirm each with a debugger, logic analyzer or oscilloscope.
  3. Settle the architecture (superloop, state machines, or RTOS tasks) before the feature list grows.
  4. Keep hardware-specific code in drivers and the rest testable on the host.
  5. Use version control from day one, and record the exact toolchain version, because compiler upgrades can change behavior.
  6. Plan how firmware will be updated in the field, whether through a bootloader, OTA or a service port, before the first units ship.

Common questions

Is embedded programming done in C or C++?

Both. C is the default on most microcontrollers and in most vendor code. C++ is common in larger projects and on more capable chips, often with features such as exceptions, RTTI and dynamic allocation restricted or disabled. Many codebases mix the two: C vendor libraries with a C++ application on top.

What are the four types of embedded systems?

A commonly cited classification groups embedded systems by function: standalone (works on its own, like a microwave controller), real-time (must meet timing deadlines, like an airbag controller), networked (communicates over a network, like an IoT sensor) and mobile (portable and battery-powered, like a fitness tracker). Real devices often fit several categories at once. Other classifications group systems by performance (small-, medium- and large-scale) instead.

What is Embedded C?

In everyday use, “Embedded C” just means C written for microcontrollers: standard C plus vendor headers, compiler extensions for interrupts and memory placement, and a style suited to constrained hardware. There’s also a formal ISO technical report (TR 18037) that defines C extensions such as fixed-point types and named address spaces, but compiler support for it varies. The Embedded C programming guide covers the practical side.

Where to go next

If you’re just starting out, a sensible order through this section is:

  1. Embedded C programming for microcontrollers
  2. Bit manipulation in embedded C
  3. The volatile keyword in embedded C
  4. How to write an interrupt service routine in C
  5. How to implement a state machine in embedded C
  6. Debugging microcontrollers with JTAG, SWD and GDB

If your device needs a display, GUI design for embedded systems covers graphics libraries, memory budgets and when embedded Android makes sense.

Keep exploring

Guides from other topics

All topics →