How do you access memory-mapped peripheral registers using pointers in Embedded C?
Memory-mapped I/O (MMIO) assigns peripheral registers addresses in the CPU address space. A load or store at such an address communicates with a peripheral rather than ordinary RAM.
1. Access through a pointer
#include <stdint.h>
volatile uint32_t *const reg = (volatile uint32_t *)0x40025400u;
void configure(void)
{
*reg = 0xF0u; // write
uint32_t value = *reg; // read
(void)value;
}
Here 0x40025400 is the GPIO Port F direction register on the TM4C123 using its APB mapping. Enable the GPIO clock and follow the device manual first. The address is device-specific.
2. Access through a macro
#define GPIOF_DIR (*(volatile uint32_t *)0x40025400u)
void set_pin4_output(void)
{
GPIOF_DIR |= (1u << 4);
}
Both forms use the same MMIO access. A constant pointer need not occupy SRAM: a compiler can optimize it into an immediate address. The macro is not inherently faster.
3. Why volatile?
The peripheral can change register values independently of the CPU. Volatile tells the compiler to perform the specified accesses instead of eliminating or caching them. It does not make a read-modify-write atomic, provide thread synchronization or guarantee hardware ordering. Use the register's required width, alignment, access semantics and barriers when required.
4. Cortex-M memory map (architectural regions)
| Address range | Typical use |
|---|---|
| 0x00000000-0x1FFFFFFF | Code / flash |
| 0x20000000-0x3FFFFFFF | SRAM |
| 0x40000000-0x5FFFFFFF | Peripherals |
| 0x60000000-0x9FFFFFFF | External RAM |
| 0xA0000000-0xDFFFFFFF | External devices |
| 0xE0000000-0xFFFFFFFF | System / vendor-specific |
The 32-bit address space spans 4 GiB, but most addresses are not necessarily backed by physical memory; some are reserved or protected. CPU general-purpose registers are accessed by instructions, not MMIO; some system control registers are memory-mapped.
Interview takeaway: For write-one-to-clear status bits use a direct mask write, not |=. Use vendor CMSIS register definitions where available.