</>EmbeddedInterview

How do you access a memory-mapped register at a fixed address?

EasyPointers & Memory

Short answer: Convert the register's address into a pointer to a volatile fixed-width integer and dereference it. The volatile makes the compiler perform every read and write exactly as written. Vendor headers (CMSIS) do the same with a struct that overlays a whole peripheral's registers.

#include <stdint.h>

#define GPIOA_BASE  0x40020000u
#define GPIOA_MODER (*(volatile uint32_t *)(GPIOA_BASE + 0x00u))
#define GPIOA_ODR   (*(volatile uint32_t *)(GPIOA_BASE + 0x14u))

void led_on(void)
{
    GPIOA_MODER = (GPIOA_MODER & ~(3u << 10)) | (1u << 10);   /* PA5 as output */
    GPIOA_ODR |= (1u << 5);                                     /* drive PA5 high */
}

The struct-overlay style (CMSIS)

typedef struct {
    volatile uint32_t MODER;    /* 0x00 */
    volatile uint32_t OTYPER;   /* 0x04 */
    volatile uint32_t OSPEEDR;  /* 0x08 */
    volatile uint32_t PUPDR;    /* 0x0C */
    volatile const uint32_t IDR;/* 0x10  read-only */
    volatile uint32_t ODR;      /* 0x14 */
    volatile uint32_t BSRR;     /* 0x18  write-only set/reset */
} GPIO_TypeDef;

#define GPIOA ((GPIO_TypeDef *)GPIOA_BASE)

GPIOA->BSRR = 1u << 5;          /* atomic set of PA5, no read-modify-write */

Use _Static_assert(offsetof(GPIO_TypeDef, ODR) == 0x14, "") to check the layout.

Important details

  • volatile is required, or the compiler may combine, reorder or remove accesses (e.g. a polling loop reading a status register once).
  • Access width: some peripherals require 32-bit accesses; using uint8_t pointers to them may fault or be ignored. Match the width the reference manual specifies.
  • Read-modify-write is not atomic. GPIOA->ODR |= x can race with an ISR modifying the same register; use set/clear registers (BSRR), bit-banding, or a critical section.
  • Write-1-to-clear status bits: SR |= FLAG would clear every flag that is set; write only the bit you mean: SR = FLAG.
  • Ordering: volatile orders accesses in the compiler, but on cores with write buffers (Cortex-M7, Cortex-A) you may need __DSB() before relying on a write having reached the peripheral (e.g. before sleeping or after clearing an interrupt flag).
  • On Linux, user space cannot use physical addresses directly; drivers use ioremap() + readl()/writel(), and user space can mmap() /dev/mem or a UIO device for experiments.