Firmware Programming

Embedded C Programming for Microcontrollers

A practical guide to embedded C: fixed-width types, register access, peripheral structs, memory-aware coding, common pitfalls, compiler flags and MISRA C.

On this page
  1. What “Embedded C” means
  2. How embedded C differs in practice
  3. Fixed-width integer types and why they matter
  4. Accessing hardware from C
  5. A minimal register-level example
  6. Memory-aware C
  7. Pitfalls specific to embedded C
  8. Compiler and linker settings worth knowing
  9. Coding standards and static analysis
  10. Structuring an embedded C project
  11. Where embedded C goes from here

C is still the main language for microcontroller firmware. Compilers exist for almost every chip, the language maps closely to the hardware, and most vendor code, drivers and example projects are written in it. If you already know C from desktop work, the syntax won’t change. What changes is how you use it. You’ll be writing to hardware registers, counting bytes of RAM, sharing data with interrupts, and paying much more attention to what the compiler actually produces.

This guide covers the practical side of embedded software development with C.

What “Embedded C” means

In everyday use, Embedded C means C written for embedded targets: standard C plus vendor header files, a few compiler-specific extensions, and a coding style suited to constrained hardware.

Embedded C vs. standard C

There’s also a formal ISO technical report, ISO/IEC TR 18037, which proposes C extensions for embedded processors. These include fixed-point arithmetic types, named address spaces (useful on chips with separate memory spaces), and basic I/O hardware addressing. Compiler support for it is uneven, though, and most embedded code you’ll see is ordinary ISO C (often C99 or C11) plus vendor extensions such as:

  • Keywords or attributes for interrupt handlers on some architectures
  • Attributes to place data or code in specific memory sections
  • Intrinsics for special CPU instructions (e.g., __WFI(), __NOP() in Arm’s CMSIS headers)

For the broader picture of what firmware is and how it runs, see the embedded firmware development overview.

How embedded C differs in practice

Desktop C Embedded C
OS loads your program and provides printf, files, memory No OS (or a tiny RTOS); you set up clocks, pins and peripherals
main() returns to the OS main() runs an infinite loop and never returns
Gigabytes of RAM, heap use is routine Kilobytes of RAM; heap use is often restricted or banned
int size rarely matters int may be 16 bits; exact widths matter for registers
Bugs crash a process Bugs can hang a device, corrupt memory silently, or damage hardware
Debug with a debugger on the same machine Debug through a probe connected to separate hardware

Fixed-width integer types and why they matter

In C, int is at least 16 bits. It’s 16 bits on 8-bit AVR and 32 bits on Arm Cortex-M. Since registers and protocols have exact widths, embedded code relies on the fixed-width types from <stdint.h>:

#include <stdint.h>

uint8_t  status;     /* exactly 8 bits, unsigned */
int16_t  temperature;/* exactly 16 bits, signed */
uint32_t ticks;      /* exactly 32 bits, unsigned */

Use unsigned types for register values and bit masks. Use <stdbool.h> for bool flags. Avoid plain char for numeric data, because whether it’s signed is implementation-defined.

Accessing hardware from C

Pointers to registers

Peripheral registers sit at fixed addresses. The classic way to access one is to cast the address to a pointer to a volatile integer:

#define GPIOA_ODR  (*(volatile uint32_t *)0x40020014u)

GPIOA_ODR |= (1u << 5);   /* set bit 5 */

The volatile qualifier tells the compiler that every read and write must actually happen. Hardware can change the value, and writes have side effects. Without it, the optimizer may remove or merge accesses. The volatile keyword guide covers this in depth.

(The address above is GPIOA’s output data register on STM32F4 parts. Always check your own chip’s reference manual.)

Peripheral structs (CMSIS style)

Vendor headers usually describe each peripheral as a struct whose members line up with its registers, and then define a pointer to the peripheral’s base address:

typedef struct {
    volatile uint32_t MODER;
    volatile uint32_t OTYPER;
    volatile uint32_t OSPEEDR;
    volatile uint32_t PUPDR;
    volatile uint32_t IDR;
    volatile uint32_t ODR;
    volatile uint32_t BSRR;
    /* ... */
} GPIO_TypeDef;

#define GPIOA ((GPIO_TypeDef *)0x40020000u)

GPIOA->ODR ^= (1u << 5);

This is the style used by Arm’s CMSIS device headers and most Cortex-M vendors. You’ll rarely write these structs yourself. Include the vendor’s device header instead.

A minimal register-level example

AVR (ATmega328P, as on an Arduino Uno). The onboard LED is on pin PB5:

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= (1 << DDB5);          /* PB5 as output */

    for (;;) {
        PORTB ^= (1 << PORTB5);   /* toggle LED */
        _delay_ms(500);
    }
}

STM32F4 (e.g., a Nucleo board with the user LED on PA5), using the vendor’s CMSIS device header:

#include "stm32f4xx.h"

int main(void)
{
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;      /* enable GPIOA clock */

    GPIOA->MODER &= ~(3u << (5 * 2));         /* clear mode bits for PA5 */
    GPIOA->MODER |=  (1u << (5 * 2));         /* 01 = general-purpose output */

    for (;;) {
        GPIOA->ODR ^= (1u << 5);
        for (volatile uint32_t i = 0; i < 500000u; i++) { }  /* crude delay */
    }
}

Two things are worth noticing. First, on most modern MCUs a peripheral does nothing until you enable its clock. Second, the busy-wait loop is fine for a first test, but real firmware should use a timer instead. The bitwise patterns used here are explained in bit manipulation in embedded C.

Memory-aware C

const and flash

On most microcontrollers, data declared const at file scope can stay in flash instead of being copied into RAM:

static const uint16_t sine_table[256] = { /* ... */ };

On Cortex-M this generally works automatically. On AVR, flash and RAM are separate address spaces, so constant tables need PROGMEM and special read functions (pgm_read_byte() and friends) to actually stay in flash.

Static allocation over malloc

Many projects avoid dynamic memory entirely, or allow it only during startup. A small heap can fragment over time, and allocation failures may appear only after long runtimes. The usual alternative is to size buffers, queues and object pools at compile time:

#define RX_BUF_SIZE 128u
static uint8_t rx_buf[RX_BUF_SIZE];

Watching the stack

Each function call and each interrupt uses stack space, and on a small MCU a stack overflow can silently corrupt other data. Watch out for:

  • Large local arrays. Make them static or global if they’re big.
  • Deep or recursive calls. Recursion is usually avoided.
  • Nested interrupts adding their frames on top of the main stack.

Many toolchains can report per-function stack usage. GCC’s -fstack-usage flag writes .su files, for example. A common runtime check is to fill the stack with a known pattern at startup and later see how much of it has been overwritten.

Pitfalls specific to embedded C

Integer promotion and signedness

C promotes types smaller than int to int before arithmetic. That can surprise you:

uint8_t a = 200, b = 100;
if (a + b > 255) { /* true: a + b is computed as int (300) */ }

uint8_t mask = 0x0F;
uint8_t inv  = ~mask;        /* ~mask is int 0xFFFFFFF0; stored as 0xF0 */

Shifting 1 into the sign bit of a signed int (1 << 31 on a 32-bit int) is undefined behavior. Use 1u << 31 or UINT32_C(1) << 31.

Floating point on MCUs without an FPU

Some cores have a hardware floating-point unit (for example, many Cortex-M4F and M7 parts, often single-precision only). Others, such as Cortex-M0/M0+ and 8-bit AVR, don’t. On those chips, the compiler emulates float and double in software, which costs flash and CPU time. Common workarounds:

  • Use integer or fixed-point math (for example, store temperature in hundredths of a degree).
  • Use float instead of double and suffix constants with f (3.3f). On FPUs that are single-precision only, double math falls back to software.

Undefined behavior and optimization

Optimizers assume your code has no undefined behavior. Signed overflow, out-of-bounds access, using uninitialized variables and strict-aliasing violations can produce code that works at -O0 and fails at -O2. If a bug appears or disappears when you change the optimization level, suspect undefined behavior or a missing volatile before you blame the compiler.

Compiler and linker settings worth knowing

With GCC-based toolchains, a few flags show up in most embedded projects:

  • -Os or -O2: optimize for size or speed. Many firmware builds use -Os.
  • -Wall -Wextra: turn on useful warnings and treat them seriously.
  • -ffunction-sections -fdata-sections with -Wl,--gc-sections: put each function and variable in its own section so the linker can drop unused ones.
  • -Wl,-Map=firmware.map: produce a map file showing where everything landed and how big it is.
  • -g: include debug info. It lives in the ELF file, not in flash, so it doesn’t make the firmware larger.

The size tool (arm-none-eabi-size firmware.elf) gives a quick summary of text, data and bss usage after each build.

Coding standards and static analysis

MISRA C is a widely used set of guidelines for C in safety-related and critical systems, originally from the automotive industry. It restricts features that tend to cause bugs, such as dynamic memory, unrestricted pointer casts and some implicit conversions. Even if your project doesn’t need formal compliance, many of its rules are good defaults.

Static analysis tools catch problems compilers miss. Options range from free tools such as cppcheck and the Clang static analyzer to commercial MISRA checkers. Running one in continuous integration is a low-effort way to find bugs early.

Structuring an embedded C project

A layout that scales reasonably well:

  • drivers/: register-level or HAL-based code for each peripheral (UART, SPI, ADC).
  • board/: pin assignments and board-specific setup.
  • app/: application logic that calls drivers through small interfaces.
  • tests/: host-side unit tests for the logic in app/.

Keep #include "stm32f4xx.h" (or your vendor’s equivalent) out of application files where possible. Logic that doesn’t touch registers can then be compiled and tested on a PC.

Where embedded C goes from here

Once register access and memory-aware habits feel natural, the next topics are:

The complete guide to firmware programming

Embedded Firmware Development: Core Programming Concepts
Read the guide

Keep exploring

Guides from other topics

All topics →