Try Embedded

Registers, volatile and const

How C talks to hardware: memory-mapped registers, what volatile and const promise, register structs and read-modify-write.

Hardware is just memory

A microcontroller's peripherals are controlled through registers: fixed addresses that the hardware watches. Writing to address 0x40020014 on an STM32F4 does not store a value in RAM. It drives the pins of port A. Reading 0x40020010 returns the voltage levels on those pins.

This is called memory-mapped I/O. C reaches a register by turning its address into a pointer and dereferencing it.

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

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

int main(void) {
  GPIOA_ODR = 0;
  GPIOA_ODR |= (1u << 5);       // drive PA5 high
  printf("ODR = 0x%08X\n", GPIOA_ODR);
  GPIOA_ODR &= ~(1u << 5);      // drive PA5 low
  printf("ODR = 0x%08X\n", GPIOA_ODR);
  return 0;
}

Read the macro from the inside out: 0x40020014u is a number, the cast makes it a pointer to a volatile uint32_t, and the outer * dereferences it. The result behaves like a variable that lives at that address. In this simulator the peripheral region is plain readable and writable memory, so you can exercise register code and inspect what it wrote.

volatile and const: two promises to the compiler

volatile and const are type qualifiers. Neither changes how a value is stored. Each one changes what the compiler is allowed to assume about it, and register code needs both.

QualifierWhat you promiseWhat the compiler may no longer do
volatileSomething outside this code may read or change the objectRemove, merge, cache or reorder accesses to it
constThis code will not write the object through this nameAccept a write through this name (it is a compile error)

They answer different questions, so they combine freely.

Why volatile

The compiler assumes that memory only changes when your code changes it. For a register that is false in both directions: hardware changes it, and writing it has effects the compiler cannot see. volatile tells the compiler that every read and every write in the source must happen, in order, exactly once.

Without volatile, an optimiser is entitled to make these transformations:

You wroteThe optimiser may produceConsequence
while (!(STATUS & READY)) { }Read STATUS once, then loop forever or neverHangs, or skips the wait
DATA = 0x01; DATA = 0x02;Only the second writeThe device never sees the first byte
(void)STATUS; to clear a flag by readingNothingThe flag is never cleared

Three kinds of object need volatile:

  1. Memory-mapped registers. Hardware changes status bits, and writes have side effects such as transmitting a byte.
  2. Variables shared between an interrupt handler and the main code. The main loop cannot see the interrupt's writes in its own control flow.
  3. Memory changed by something outside the program flow: DMA, another core, a debugger.

The second kind catches everyone once. The flag is set by an interrupt, so nothing in wait_for_data's own code can change it:

static bool data_ready;              // set in the UART interrupt

void wait_for_data(void) {
  while (!data_ready) { }            // the optimiser may read once and spin forever
}

With static volatile bool data_ready; the compiler must reload the flag on every iteration.

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

#define STATUS (*(volatile uint32_t *)0x40011000u)
#define DATA   (*(volatile uint32_t *)0x40011004u)
#define RXNE   (1u << 5)

int main(void) {
  STATUS = RXNE;            // pretend the hardware received a byte
  DATA = 'A';

  if (STATUS & RXNE) {      // each read below is a real bus access
    uint32_t byte = DATA;
    printf("received '%c'\n", (char)byte);
  }
  return 0;
}

What volatile does not do

volatile is often over-trusted. It guarantees that accesses happen, in program order relative to other volatile accesses. It does not give you:

  • Atomicity. counter++ on a volatile variable is still a read, an add and a write, and an interrupt can run in the middle and lose an update.
  • Ordering with ordinary variables. The compiler may move non-volatile accesses across a volatile one.
  • Ordering in hardware. On cores with caches or write buffers you also need memory barriers (__DMB(), __DSB()) when DMA or another bus master is involved.
  • Thread safety. Between RTOS tasks use a mutex, a queue or a real atomic type (_Atomic, <stdatomic.h>).

Note: For a variable shared with an interrupt, the usual recipe is volatile for visibility plus a short critical section (disable that interrupt, or all of them briefly) around any read-modify-write.

const in firmware

const is about the name, not the memory: a const int *p can point at a perfectly writable variable and only stops writes through `p`. The pointers guide shows how to read const in pointer declarations. In firmware it earns its keep in three places:

  1. Function parameters. const uint8_t *buf documents that a driver only reads the caller's buffer, and the compiler enforces it.
  2. Lookup tables. A static const table at file scope goes into flash instead of RAM with Arm, RISC-V and most other embedded toolchains, so a 512-entry sine table costs no RAM at all. The AVR is the classic exception: avr-gcc copies const data to RAM unless it is marked PROGMEM (or __flash).
  3. Configuration. Pin maps and calibration constants that must never change at run time.

Pitfall: Casting const away and writing through the result is undefined behaviour if the object was defined const. On a microcontroller it may live in flash, and the write either faults or silently does nothing.

const volatile

The two combine for a register the program may not write but whose value changes on its own, such as a status register:

typedef struct {
  volatile uint32_t CR;          // control: read and write
  const volatile uint32_t SR;    // status: hardware writes, software only reads
  volatile uint32_t DR;          // data
} uart_regs_t;

Declaring SR as const volatile makes an accidental UART1->SR = 0; a compile error while still forcing every read to reach the hardware. Memory written by DMA that a module only reads is another example.

Describing a peripheral with a struct

A peripheral has several registers at consecutive addresses. Rather than one macro per register, lay a struct over the block and point it at the base address. This is how the CMSIS headers shipped by every Arm vendor are written.

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

typedef struct {
  volatile uint32_t MODER;    // 0x00
  volatile uint32_t OTYPER;   // 0x04
  volatile uint32_t OSPEEDR;  // 0x08
  volatile uint32_t PUPDR;    // 0x0C
  volatile uint32_t IDR;      // 0x10
  volatile uint32_t ODR;      // 0x14
  volatile uint32_t BSRR;     // 0x18
} gpio_t;

#define GPIOA ((gpio_t *)0x40020000u)

int main(void) {
  GPIOA->MODER = (GPIOA->MODER & ~(3u << 10)) | (1u << 10);   // PA5 as an output
  GPIOA->ODR |= (1u << 5);

  printf("ODR is at offset 0x%02X\n", (unsigned)offsetof(gpio_t, ODR));
  printf("MODER = 0x%08X, ODR = 0x%08X\n", GPIOA->MODER, GPIOA->ODR);
  return 0;
}

The struct only works if each member lands on the documented offset. When the datasheet skips addresses, fill the gap with a reserved member, and pin the layout down so a mistake fails to compile:

typedef struct {
  volatile uint32_t CR1;     // 0x00
  volatile uint32_t CR2;     // 0x04
  uint32_t RESERVED0[2];     // 0x08, 0x0C
  volatile uint32_t SR;      // 0x10
} timer_regs_t;

_Static_assert(offsetof(timer_regs_t, SR) == 0x10, "SR offset");

Read-modify-write and how it goes wrong

reg |= mask is three operations: read the register, change the value, write it back. Two problems follow.

Lost updates. If an interrupt changes the same register between the read and the write, the write puts back the old value of the bits the interrupt changed. Its update is lost. This is the most common race condition in firmware, and it is intermittent, because it depends on an interrupt arriving in a window a few instructions wide.

Registers that are not plain storage. Read-modify-write assumes that writing back what you read is harmless. For many registers it is not.

Access typeBehaviourCorrect way to clear bit n
Read/write (rw)Stores what you writereg &= ~(1u << n)
Write 1 to clear (rc_w1)Writing 1 clears the flag; writing 0 does nothingreg = (1u << n)
Write 0 to clear (rc_w0)Writing 0 clears; writing 1 does nothingreg = ~(1u << n)
Read to clearReading the register clears itRead it once and keep the value
Write onlyReads return zero or garbageNever use |= or &=
#include <stdio.h>
#include <stdint.h>

int main(void) {
  // Pretend this is a write-1-to-clear status register with four flags pending.
  uint32_t written;

  uint32_t sr = 0x0F;
  sr |= (1u << 1);              // WRONG: writes 1 to every pending flag
  written = sr;
  printf("with |= the bus sees 0x%02X: all four flags are acknowledged\n", written);

  sr = (1u << 1);               // RIGHT: a single 1, zeros elsewhere
  written = sr;
  printf("with =  the bus sees 0x%02X: only flag 1 is acknowledged\n", written);
  return 0;
}

Atomic set and clear registers

To avoid read-modify-write on outputs, many MCUs provide registers where only the 1 bits act. On STM32, writing a 1 to bit n of BSRR sets pin n, and writing a 1 to bit n + 16 resets it. Zeros do nothing.

GPIOA->BSRR = (1u << 5);        // set PA5: one write, nothing to interrupt
GPIOA->BSRR = (1u << (5 + 16)); // reset PA5

There is no read, so there is nothing to lose. Use these registers whenever a port is shared between interrupt and main code.

Waiting for hardware

Hardware takes time, so drivers wait for status bits. Every wait needs an exit, or one faulty peripheral hangs the product.

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

#define UART_SR  (*(volatile uint32_t *)0x40011000u)
#define UART_TXE (1u << 7)

static bool wait_tx_ready(uint32_t max_polls) {
  while (max_polls--) {
    if (UART_SR & UART_TXE) return true;
  }
  return false;                 // let the caller decide what a timeout means
}

int main(void) {
  UART_SR = 0;
  printf("never ready: %d\n", wait_tx_ready(1000));
  UART_SR = UART_TXE;
  printf("ready:       %d\n", wait_tx_ready(1000));
  return 0;
}

A poll count is a crude timeout, because its duration depends on the clock and the optimisation level. Production code compares a tick counter instead; the timing guide shows how to do that safely.

Common mistakes

  • Forgetting volatile on a register or on a flag shared with an interrupt.
  • Trusting volatile to make a read-modify-write safe from interrupts. It does not.
  • Using |= on a write-1-to-clear or write-only register.
  • Writing a field in two steps (clear, then set) so the register briefly holds an invalid value.
  • Configuring a peripheral before its clock is enabled. Writes to an unclocked peripheral are ignored.
  • Assuming a register reads back what was written. Many bits are reserved, self-clearing or read-only.

Interview question: Explain *(volatile uint32_t *)0x40021000 = 1; piece by piece.

Answer: 0x40021000 is an integer. (volatile uint32_t *) casts it to a pointer to a 32-bit unsigned value that may change outside the compiler's knowledge. The leading * dereferences that pointer, so the assignment performs one 32-bit write of the value 1 to that address. volatile guarantees the write is emitted even if the compiler cannot see anything reading it.

Interview question: Can a variable be both const and volatile? Give an example.

Answer: Yes. const restricts what this code may do; volatile says something else may change the value, so every read must be performed. A read-only hardware status register is the standard example: #define STATUS (*(const volatile uint32_t *)0x40011000u). Another is a buffer written by DMA that this module only reads.

Interview question: Is volatile enough to make a counter shared with an interrupt safe?

Answer: No. volatile makes each access happen, but counter++ is three steps: load, add, store. If the interrupt runs between the load and the store, one increment is lost. Protect the read-modify-write with a critical section, use an atomic instruction or <stdatomic.h>, or restructure so only one side ever writes the variable.

In the product: a battery management system

A BMS reads each cell's voltage from an ADC's data register and must react within microseconds. The register is volatile: without it the compiler may read it once and never again.

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

// On the device this would be a fixed address such as (*(volatile uint16_t *)0x40012440).
volatile uint16_t ADC_DATA = 0;

int main(void) {
  for (int sample = 0; sample < 3; sample++) {
    ADC_DATA = (uint16_t)(3400 + sample * 450);   // the hardware updating the register
    uint16_t mv = ADC_DATA;                        // volatile: a real read every time
    printf("cell: %u mV%s\n", mv, mv > 4200 ? "  -> open contactor" : "");
  }
  return 0;
}

Build it: configure the lamp's pins through their registers

This is step 1 of the module project, a smart LED lamp. Its LED driver is fed by a timer's PWM output on PA6, the touch button is on PA0, and status LEDs sit on PA1 and PA2. Each pin's job is set by fields in the GPIO port's registers, and setting one pin must never disturb another.

Lab: Pin configuration helpers on real register fields

The register map is provided. Write three helpers; each changes only its pin's field, with a read-modify-write:

  • pin_mode(g, pin, mode): MODER has 2 bits per pin (MODE_INPUT 0, MODE_OUTPUT 1, MODE_ALT 2, MODE_ANALOG 3).
  • pin_pull(g, pin, pull): PUPDR has 2 bits per pin (PULL_NONE 0, PULL_UP 1, PULL_DOWN 2).
  • pin_af(g, pin, af): the alternate function number (0 to 15) has 4 bits per pin, in AFR[0] for pins 0 to 7 and AFR[1] for pins 8 to 15.

Then lamp_pins_init() sets up the lamp: PA6 as alternate function 2 (the timer's PWM), PA0 as an input with a pull-up, PA1 and PA2 as outputs. The debugger's pins PA13 and PA14 must keep their reset setting.

Going deeper

Interview question: How do you make sure a BMS reacts to an over-voltage within its deadline?

Answer: Work back from the requirement: the cell's damage time sets a reaction deadline, which bounds the sampling rate, the filtering (how many samples must agree) and the path from detection to opening the contactor. Detect in an interrupt or a high-priority task with a measured worst-case latency, open the contactor directly from there, and back it up with an independent hardware comparator that trips without software. Then test it with injected faults and measure the reaction on a scope.

Interview question: How does a write-1-to-clear register differ from a normal register, and how do you clear one flag?

Answer: In a write-1-to-clear (rc_w1) register, writing a 1 to a bit clears that flag and writing 0 has no effect, so the register does not store what you write. To clear only flag n, write a value with only that bit set, SR = 1u << n;. Using SR |= 1u << n would read all pending flags and write them back as ones, clearing every pending flag and losing events.

Interview question: Why should register struct members be declared volatile individually rather than declaring the pointer to the struct volatile?

Answer: Both work in C, but putting volatile on each member, as CMSIS headers do, makes every access volatile wherever the struct is used, including copies of the pointer and functions that take a pointer to the struct, so it cannot be forgotten. It also allows marking read-only status registers const volatile individually and leaving reserved padding non-volatile.

Explain it: In your own words, explain why the compiler might remove a loop that waits for a hardware status bit, and how to stop it.

Answer: The compiler assumes memory only changes when the program's own code changes it. A loop that just reads a status register and checks a bit appears to read the same unchanged value every time, so the optimiser may read it once before the loop and either skip the loop or spin forever on the stale value. Declaring the register access as volatile tells the compiler the value can change outside the program, so it must perform a real read on every iteration.