CodeBlanks Logo Icon CodeBlanks

Memory-mapped I/O

Learn the memory-mapped I/O concept.

Memory-mapped I/O

Memory-mapped I/O (MMIO) maps hardware registers to memory addresses. A GPIO pin corresponds to a specific memory address; writing to that address changes the pin, reading gives the pin state.

In C this is done through a pointer: volatile unsigned int *reg = (volatile unsigned int *)0x40021000;. The volatile keyword is critical: it tells the compiler not to optimize this variable. The hardware can change the value at any time; caching would give wrong results. MMIO is the most fundamental hardware access method in embedded C.

Why is volatile important?

Without volatile, the compiler can cache a register read. For example, in while (*reg & 1) the compiler might read *reg once and store the value; even if the hardware register changes, the loop spins forever.

With volatile, the compiler re-reads the register every iteration. This is mandatory for interrupt flags and hardware status registers. In embedded C, every hardware register is declared volatile. This ensures the software always sees hardware changes. Remember: volatile does not provide thread safety; it only prevents optimization.

Practice Simulate a GPIO register

Define static volatile unsigned int gpio_data = 0; (fake register). In int main(void) write to the register with gpio_data = 1;. Read and print with printf("GPIO: %d\n", gpio_data).

Starter code

main.c
#include <stdio.h>

// sahte GPIO yazmacı tanımla (volatile)
// main'de yazmaca yaz ve oku

Sample solution

main.c
#include <stdio.h>

static volatile unsigned int gpio_data = 0;

int main(void) {
    gpio_data = 1;
    printf("GPIO: %d\n", gpio_data);
    return 0;
}

Expected output

GPIO: 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the volatile keyword

Question
____ unsigned int gpio_data = 0;
Answer
volatile unsigned int gpio_data = 0;

Explanation: volatile tells the compiler not to optimize.

2 Which qualifier is a hardware register declared with?

  • static
  • const
  • volatile Correct answer
  • auto

Explanation: volatile is mandatory for hardware registers.

3 Match MMIO concept

Term Meaning
volatile No optimization
Register Hardware address
Pointer Address access
MMIO Memory-mapped I/O

All lessons in Expert