---
title: Pointers and memory-mapped registers
heading: Lighting an LED by writing to an address
eyebrow: C8 · Lesson 18 · Pointers and memory-mapped registers
xp: 60
---

::: hook
How does a program turn on an LED? On almost every microcontroller the answer is a store instruction. The chip's peripherals (GPIO pins, timers, serial ports, ADCs) each have registers that sit at fixed addresses in the memory map. Writing a word to the GPIO output register drives pins high or low; reading the input register returns what the pins see right now. In C, those addresses are reached through pointers. On this board, the LEDs are at 0x20000 and the switches at 0x20004.

::: play
- Press Run, then click the switches. The program copies them to the LEDs over and over.
- Step it instead and watch t2. Which instruction reads the switches, and which one lights the LEDs?
- The C uses `volatile`. What would go wrong without it?
:::
:::

```sim cpu
c:
volatile unsigned *leds = (unsigned *) 0x20000;
volatile unsigned *switches = (unsigned *) 0x20004;

while (1) {
    *leds = *switches;
}
asm:
    li t0, 0x20000      # the LEDs' address      #@1
    li t1, 0x20004      # the switches' address  #@2
loop:
    lw t2, 0(t1)        # read the switches      #@5
    sw t2, 0(t0)        # write the LEDs         #@5
    j loop                                       #@4
show: t2
hex: t0, t1
leds: on
switches: on
forever: on
speed: 12
```

::: predict
## Without `volatile`, what is a compiler allowed to do with `while (1) { *leds = *switches; }`?

- [ ] Nothing different: it must do every read and write as written
- [x] Read the switches once and keep writing that same value, so the LEDs never follow the switches
- [ ] Refuse to compile the loop
- [ ] Skip the loop entirely

::: reveal
Read once and repeat. As far as C knows, ordinary memory only changes when the program writes it, and nothing in the loop writes `*switches`, so reading it every time looks wasted. An optimizing compiler may move the read out of the loop. `volatile` tells it that the location can change, or act, on its own, so every read and write in the source must really happen, in order. Every pointer to a hardware register should be `volatile`.
:::
:::

::: nameit
## Pointers, device registers and bit manipulation

**Pointers.** A pointer is a variable holding an address. `*p = v` stores v at that address (`sw`); `x = *p` loads from it (`lw`). `p + k` for an `int *` points k elements, 4k bytes, further on. A pointer to a device register is just an address cast to a pointer type:

```
volatile unsigned *leds = (unsigned *) 0x20000;
*leds = 0x0F;           // the four low LEDs on
```

**Memory-mapped I/O.** Device registers sit in the address space. A store to one doesn't save data for later; it acts, driving pins or starting a transfer. A load returns the device's state at that moment. This board's devices are in the table in lesson 6.

**Changing one bit.** Device registers pack many controls into one word, one bit each, so firmware changes a single bit without disturbing the others:

| C | Does | Assembly |
|---|---|---|
| `r |= (1 << k)` | sets bit k | `or` with the mask |
| `r &= ~(1 << k)` | clears bit k | `and` with the inverted mask |
| `r ^= (1 << k)` | flips bit k | `xor` with the mask |
| `(r >> k) & 1` | reads bit k | `srli`, `andi 1` |

Each of the first three is a **read-modify-write**: load the register, change one bit, store it back. That's three instructions, and if an interrupt (lesson 25) changes the same register between the load and the store, its change is lost, so firmware guards these sequences or uses hardware that sets and clears bits in one write. (Many microcontrollers provide separate set and clear registers for exactly this reason.)
:::

```sim cpu
    li t0, 0x20000      # the LEDs
    li t1, 1            # the lit LED, as a bit
next:
    sw t1, 0(t0)        # show it
    li t2, 100          # wait a while
wait:
    addi t2, t2, -1
    bnez t2, wait
    slli t1, t1, 1      # move to the next LED
    andi t1, t1, 0xFF   # keep 8 bits
    bnez t1, next
    li t1, 1            # past the last LED: start again
    j next
show: t1, t2
hex: t0
leds: on
forever: on
speed: 900
```

An LED chaser: one lit LED moving along, with a delay loop of 200 instructions between moves. Real firmware would use a timer instead of a delay loop, so the processor can do other work (or sleep) while it waits.


::: example
## The LED register holds 0x35. Firmware sets bit 1, then clears bit 4. What does it hold afterward?

::: solution
1. **Write it in binary.** 0x35 is 0011 0101.
2. **Set bit 1.** That gives 0011 0111 = 0x37.
3. **Clear bit 4.** That gives 0010 0111 = 0x27.

**Answer:** the register holds 0x27.
:::
:::

::: example
## Read bit 6 of the switches into t1.

::: solution
1. **Read the switches.** `li t0, 0x20000`, then `lw t1, 4(t0)`.
2. **Move bit 6 to the bottom.** `srli t1, t1, 6`.
3. **Keep only that bit.** `andi t1, t1, 1`.

**Answer:** `li t0, 0x20000`, `lw t1, 4(t0)`, `srli t1, t1, 6`, `andi t1, t1, 1`.
:::
:::

::: example
## A control register holds 0xA5. Its bits 7:4 are a speed field. Set the field to 9 without disturbing the other bits.

::: solution
1. **Clear the field, then OR in the new value shifted into place.**
   $$(\text{0xA5}\ \&\ \sim\text{0xF0}) \mid (9 \ll 4)$$
2. **Work it out.** The AND leaves 0x05, the shifted 9 is 0x90, and the result is 0x95.
3. **In assembly.** `andi t1, t0, -241` (the mask ~0xF0 sign-extends from 12 bits), `ori t1, t1, 0x90`, then the store.
4. **Why clear first.** ORing without clearing first would leave 0xB5, because the old field's 1 bits survive.

**Answer:** the register holds 0x95.
:::
:::

::: check
given: k = 0..3 int; a = 16..255 int; let v = a - (floor(a/2^k) - 2*floor(a/2^(k + 1)))*2^k
answer: v + 2^k
base: 16
width: 2

## An 8-bit LED register holds 0x{v:hex2}, with LED {k} off. What value turns LED {k} on and leaves the others as they are?

::: right
Right: 0x{answer}. OR-ing with $2^{\given{k}}$ sets that bit and keeps every other bit.
:::

::: misses
- [2^k] That turns LED {k} on but turns the others off. OR the mask with the old value.
- [v] That's the value it already holds.
- [any] Not yet. Set bit {k}: add (or OR in) $2^{\given{k}}$.
:::
:::

::: check
given: k = 0..7 int
answer: 255 - 2^k
base: 16
width: 2

## What 8-bit mask do you AND a register with to clear bit {k} and keep the others?

::: right
Right: 0x{answer}. Every bit 1 except bit {k}, which is `~(1 << k)`.
:::

::: misses
- [2^k] AND with that keeps only bit {k}. Invert it.
- [any] Not yet. All ones, except a 0 in bit {k}.
:::
:::

::: check
kind: asm
given: k = 0..7 int; a = 0..255 int; let v = a - (floor(a/2^k) - 2*floor(a/2^(k + 1)))*2^k
expect: leds = v + 2^k

## The LEDs already show a pattern. Turn on LED {k} (bit {k}) without changing any of the others. Read the pattern from the LED register; don't write it in.

```asm starter
    li t0, 0x20000
    li t1, v            # the pattern the LEDs start with
    sw t1, 0(t0)
    # your code: read the LEDs, set bit k, write them back
    ebreak
```

```asm solution
    li t0, 0x20000
    li t1, v
    sw t1, 0(t0)
    lw t1, 0(t0)        # read
    li t2, 1
    slli t2, t2, k      # the mask 1 << k
    or t1, t1, t2       # modify
    sw t1, 0(t0)        # write
    ebreak
```

::: right
Right: read, modify, write. The same three steps change one pin on a real GPIO port.
:::
:::

::: check
kind: asm
given: s = 1..254 int
setup: switches = s
expect: leds = 255 - s

## Light each LED whose switch is off, and turn off each LED whose switch is on. (Read the switches once, then stop.)

```asm starter
    li t0, 0x20000
    ebreak
```

```asm solution
    li t0, 0x20000
    lw t1, 4(t0)        # the switches, at 0x20004
    xori t1, t1, 0xFF   # flip the 8 low bits
    sw t1, 0(t0)        # the LEDs
    ebreak
```

::: right
Right. XOR with 0xFF flips the eight low bits. One base register and offsets reach both devices.
:::
:::

::: check
given: s = 0..255 int; k = 0..7 int
answer: floor(s/2^k) - 2*floor(s/2^(k + 1))
tolerance: 0

## The switch register reads 0x{s:hex2}. What is `(*switches >> {k}) & 1`?

::: right
Right: {answer}. Shift bit {k} down to bit 0, then keep only that bit.
:::

::: misses
- [any] Not yet. Write 0x{s:hex2} in binary and read bit {k}, counting from 0 at the right.
:::
:::

::: check
kind: choice

## What does `volatile` on a pointer to a device register guarantee?

- [ ] The register is faster to access
- [x] Every read and write in the code really happens, in order
- [ ] The value can't change
- [ ] Interrupts are turned off while it's used

::: right
Right. It stops the compiler from caching, merging or dropping accesses it would think are redundant for ordinary memory.
:::

::: misses
- [1] It doesn't change the hardware at all; it changes what the compiler may do.
- [3] The opposite: it says the value can change without the program writing it.
- [4] That needs separate code; `volatile` only affects the compiler.
:::
:::

::: check
kind: parts
given: v = 165 | 60 | 126 | 211; f = 2 | 9 | 13

## A register holds {v:hex2}. Set its bits 7:4 to {f} and leave the others alone.

::: part
answer: v - 16*floor(v/16) + 16*f
tolerance: 0
base: 16
width: 2

### What does it hold afterward?

::: misses
- [v + 16*f] Clear the field before you OR in the new value.
- [any] Keep the low nibble and put f in the high one.
:::
:::

::: part
answer: v - 16*floor(v/16)
tolerance: 0
base: 16
width: 2

### What's left after the AND with ~0xF0, before the OR?

::: misses
- [any] Only the low four bits survive.
:::
:::
:::

::: check
kind: asm
given: v = 0..255 int; k = 0..7 int
setup: a0 = v; a1 = k
expect: a2 = v + 2^k*(1 - 2*(floor(v/2^k) - 2*floor(v/2^(k + 1))))

## Toggle bit a1 of a0 and put the result in a2.

```asm starter
    mv a2, a0
    ebreak
```

```asm solution
    li t0, 1
    sll t0, t0, a1
    xor a2, a0, t0
    ebreak
```

::: right
Right. XOR with a one-bit mask flips that bit and leaves the rest.
:::
:::

::: explain
## To turn on one LED in an 8-bit LED register, why does firmware read the register, change one bit and write it back, instead of just writing a value?

::: model
The register controls all eight LEDs at once, and a write sets every bit. If the firmware wrote just the bit it wanted, say 0x08, it would turn LED 3 on and every other LED off. To change only one bit, it has to know the current state of the others, so it reads the register, ORs in the one bit (or ANDs it out, or XORs it), and writes the whole word back with the other bits unchanged.
:::
:::

::: practice

::: check
given: k = 0..3 int; a = 16..255 int; let v = a - (floor(a/2^k) - 2*floor(a/2^(k + 1)))*2^k
answer: v + 2^k
base: 16
width: 2

## Register 0x{v:hex2}; set bit {k}. New value?

::: misses
- [2^k] Keep the other bits.
- [any] OR in $2^{\given{k}}$.
:::
:::

::: check
given: k = 0..7 int
answer: 255 - 2^k
base: 16
width: 2

## 8-bit mask to clear bit {k}?

::: misses
- [any] `~(1 << k)`: all ones but bit {k}.
:::
:::

::: check
kind: asm
given: k = 0..7 int; v = 0..255 int
expect: leds = v + 2^k*(1 - 2*(floor(v/2^k) - 2*floor(v/2^(k + 1))))

## The LEDs show a pattern. Flip LED {k} (on to off, or off to on), leaving the rest.

```asm starter
    li t0, 0x20000
    li t1, v
    sw t1, 0(t0)
    ebreak
```

```asm solution
    li t0, 0x20000
    li t1, v
    sw t1, 0(t0)
    lw t1, 0(t0)
    li t2, 1
    slli t2, t2, k
    xor t1, t1, t2
    sw t1, 0(t0)
    ebreak
```

::: misses
- [any] XOR with the mask 1 << {k}.
:::
:::
:::
