---
title: Blinking an LED in C
heading: Registers, pointers and the instructions they become
eyebrow: C12 · Lesson 3 · Blinking an LED in C
xp: 40
---

::: hook
In MicroPython, `led.on()` hides a register write behind a method call. In C there's nothing to hide behind: a peripheral register is a memory address, and the program writes to it through a pointer. `GPIO_SET = 1 << 0;` turns into three machine instructions, which take 300 ns on this board, against MicroPython's 40 µs for the same job. That speed, and seeing exactly what the processor does, is why C is the language of firmware. The cost is that the program has to manage everything itself, including how long a delay lasts.
:::

::: play
- The C program blinks the LED on P0 with a delay loop that just counts. Open *The compiled program* to see the RISC-V instructions it became: `GPIO_SET = 1 << 0` is a `li`, a `lui` and an `sw` to address 0x4000_0010.
- Each pass of the delay loop takes 6 cycles, so `delay(16667)` wastes about 100,000 cycles: 10 ms. Halve the number and run again.
- Press Debug and step through it a line at a time: watch the LED change when the `GPIO_SET` line runs, and `i` count up inside `delay`.
:::
:::

```sim board
lang: c
attach: led P0 | red
scope: P0 | 0..60 ms
run: 100 ms
show: asm, debug
code:
#include "board.h"

// Waste time: each pass of this loop takes 6 clock cycles.
void delay(uint32_t n) {
    for (volatile uint32_t i = 0; i < n; i++)
        ;
}

int main(void) {
    GPIO_DIR = 1 << 0;         // P0 is an output
    while (1) {
        GPIO_SET = 1 << 0;     // LED on
        delay(16667);          // about 10 ms
        GPIO_CLR = 1 << 0;     // LED off
        delay(16667);
    }
}
```

::: predict
## The loop `while (1) GPIO_TOGGLE = 1;` compiles to four instructions per pass. At what frequency does P0 square-wave?

- [ ] 10 MHz
- [ ] 2.5 MHz
- [x] 1.25 MHz
- [ ] 12.5 kHz

::: reveal
1.25 MHz. Each pass toggles once and takes 4 cycles (400 ns), so a full period, high then low, takes 8 cycles: $10\text{ MHz}/8 = 1.25$ MHz. The same loop in MicroPython toggles once every 40 µs, a 12.5 kHz square wave: a hundred times slower.
:::
:::

::: nameit
## A register is a pointer

`board.h` defines each register as a dereferenced pointer to its address:

```c
#define GPIO_SET (*(volatile uint32_t *)0x40000010)
```

Reading the right to left: the number 0x4000_0010, cast to a pointer to a 32-bit unsigned integer, then dereferenced, so `GPIO_SET = x` stores x at that address and `y = GPIO_IN` loads from one. `volatile` tells the compiler every access must really happen (lesson 4).

## SET, CLR and TOGGLE

`GPIO_OUT` holds every pin's level at once. Changing one pin by reading OUT, changing a bit and writing it back takes three steps, and an interrupt between them can lose another pin's change. The write-only registers act on just the bits written as 1:

| Write | Effect |
|---|---|
| `GPIO_SET = m` | pins in m go high |
| `GPIO_CLR = m` | pins in m go low |
| `GPIO_TOGGLE = m` | pins in m flip |

with the mask `m = 1 << n` for pin n, or several ORed together: `(1 << 0) | (1 << 3)`.

## Delays by counting

A busy-wait loop burns cycles. Its length is the cycles per pass times the passes, so it has to be measured or counted from the compiled code (6 cycles per pass here) and changes with the compiler. A delay that reads a clock is more robust:

```c
void wait_cycles(uint32_t n) {
    uint32_t start = SYS_CYCLES;
    while (SYS_CYCLES - start < n) ;   // correct even when the counter wraps
}
```

The subtraction of unsigned values gives the elapsed count even across the counter's wrap from $2^{32} - 1$ to 0.
:::

::: example
## How many passes of the 6-cycle delay loop make 1 ms?

::: solution
1. **Cycles in 1 ms.** At 10 MHz, 1 ms is 10,000 cycles.
2. **Passes of the loop.** Each pass takes 6 cycles:
   $$\frac{10\,000}{6} \approx 1667\ \text{passes}$$
3. **The call's own cost.** The call itself adds a few cycles, which only matters for very short delays.

**Answer:** about 1667 passes make 1 ms.
:::
:::

::: example
## What does `GPIO_SET = 1 << 3;` compile to, and how long does it take?

::: solution
1. **Fold the constant.** The compiler folds `1 << 3` to 8.
2. **Load the value.** `li t0, 8` puts the value in a register.
3. **Load the address.** `lui t1, 0x40000` loads the top of the address.
4. **Store.** `sw t0, 16(t1)` stores the value at
   $$\begin{aligned} &\text{0x4000\_0000} + 16 \\ &= \text{0x4000\_0010} \end{aligned}$$
5. **Time it.** Three instructions take 300 ns.

**Answer:** it compiles to `li t0, 8`, `lui t1, 0x40000` and `sw t0, 16(t1)`, three instructions that take 300 ns.
:::
:::

::: example
## A C loop toggles a pin with a store, then branches back: about 3 instructions per toggle. What frequency comes out, against MicroPython's 12.5 kHz?

::: solution
1. **One toggle.** 3 instructions at 100 ns:
   $$3 \times 100\ \text{ns} = 300\ \text{ns}$$
2. **One cycle.** Two toggles make 600 ns, so
   $$\begin{aligned} f &= \frac{1}{600\ \text{ns}} \\ &\approx 1.67\ \text{MHz} \end{aligned}$$
3. **Compare with MicroPython.** Its cycle takes 80 µs:
   $$\frac{80\ \mu\text{s}}{600\ \text{ns}} \approx 133$$
   so C is 133 times faster.
4. **A better way.** Even so, a hardware timer or PWM channel is the better way to make a frequency, because it keeps running steadily while the processor does other work.

**Answer:** about 1.67 MHz, 133 times faster than MicroPython's 12.5 kHz.
:::
:::

::: check
given: t = 1 | 5 | 20 | 100; k = 4 | 6 | 9
answer: t*10000/k
tolerance: 0.5%

## A busy-wait loop takes {k} cycles per pass. About how many passes make {t} ms on the 10 MHz board?

::: right
Right. $t \times 10^4/k$ = {answer} passes.
:::

::: misses
- [t*10000] That counts cycles; each pass is {k} of them.
- [any] Not yet. Cycles in {t} ms, divided by {k}.
:::
:::

::: check
given: k = 2 | 3 | 4 | 5 | 8
answer: 10000/(2*k)
unit: kHz
tolerance: 0.5%

## A loop toggles a pin once per pass, and each pass takes {k} cycles. What's the frequency of the square wave?

::: right
Right. A period is two passes: $10\text{ MHz}/(2k)$ = {answer} kHz.
:::

::: misses
- [10000/k] One pass is only half a period: the pin goes up in one pass and down in the next.
- [any] Not yet. Two passes per period.
:::
:::

::: check
given: a = 0 | 1 | 2; b = 3 | 5 | 13
base: 16
answer: 2^a + 2^b

## What mask, in hex, selects pins P{a} and P{b} together?

::: right
Right. `(1 << {a}) | (1 << {b})` = {answer:hex4}.
:::

::: misses
- [a + b] That adds the pin numbers; the mask sets one bit for each.
- [any] Not yet. Set bit {a} and bit {b}.
:::
:::

::: check
given: off = 16 | 20 | 24 | 36
base: 16
answer: 1073741824 + off

## A GPIO register sits at offset {off} (decimal) from the GPIO base, 0x4000_0000. What address does the C header cast to a pointer, in hex?

::: right
Right. {answer:hex8}.
:::

::: misses
- [any] Not yet. Add the offset; {off} is {off:hex2} in hex.
:::
:::

::: check
given: n = 3 | 4 | 5; us = 40
answer: us*1000/(n*100)
tolerance: 0.5%

## A register write takes {n} instructions in C (100 ns each) and 40 µs in MicroPython. How many times faster is C?

::: right
Right. 40 µs over {n} × 100 ns: {answer} times.
:::

::: misses
- [any] Not yet. Divide the two times.
:::
:::

::: check
kind: choice

## Another part of the program can change other pins of GPIO_OUT from an interrupt. Which line turns P2 on safely?

- [ ] `GPIO_OUT = 1 << 2;`
- [ ] `GPIO_OUT = GPIO_OUT | (1 << 2);`
- [x] `GPIO_SET = 1 << 2;`
- [ ] `GPIO_TOGGLE = 1 << 2;`

::: misses
- [1] That writes every pin, turning all the others off.
- [2] A read, an OR and a write: an interrupt between the read and the write loses its own change.
- [4] Toggling turns it on only if it was off.
:::
:::

::: check
kind: c
given: A = 0 | 1 | 2; B = 3 | 4 | 5
attach: led P{A}; led P{B}
run: 0.1
expect: level(P{A}) = 1; level(P{B}) = 1

## LEDs are wired to P{A} and P{B} (the program can use the constants `A` and `B`). Make both pins outputs and turn both LEDs on.

```c starter
#include "board.h"

int main(void) {
    return 0;
}
```

```c solution
#include "board.h"

int main(void) {
    GPIO_DIR = (1 << A) | (1 << B);
    GPIO_SET = (1 << A) | (1 << B);
    return 0;
}
```

::: right
Right. One write to DIR makes both pins outputs, and one write to SET drives both high.
:::
:::

::: check
kind: c
given: HALF = 5 | 10 | 25
attach: led P0
run: 0.5
expect: period(P0) = 2*HALF ms ± 0.1%; duty(P0) = 50 % ± 1

## Blink P0 with `HALF` ({HALF}) ms on and {HALF} ms off, timing it with SYS_CYCLES (10 cycles per microsecond).

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1;
    while (1) {
        GPIO_TOGGLE = 1;
    }
}
```

```c solution
#include "board.h"

void wait_cycles(uint32_t n) {
    uint32_t start = SYS_CYCLES;
    while (SYS_CYCLES - start < n) ;
}

int main(void) {
    GPIO_DIR = 1;
    while (1) {
        GPIO_TOGGLE = 1;
        wait_cycles(HALF * 10000);
    }
}
```

::: right
Right. Timing from the cycle counter doesn't depend on how many cycles the loop itself takes.
:::
:::

::: check
kind: parts
given: t = 0.1 | 1 | 10; k = 4 | 6 | 8

## A delay loop takes {k} cycles per pass on the 10 MHz board.

::: part
answer: t*1e4/k
tolerance: 0.5%

### How many passes make {t} ms?

::: misses
- [any] Cycles needed over cycles per pass.
:::
:::

::: part
answer: k*100
unit: ns
tolerance: 0.5%

### How long is one pass?

::: misses
- [any] {k} × 100 ns.
:::
:::
:::

::: check
kind: parts
given: k = 2 | 3 | 5

## A C loop toggles a pin every {k} instructions of one cycle each.

::: part
answer: 1e7/(2*k)/1e6
unit: MHz
tolerance: 0.5%

### What frequency comes out?

::: misses
- [1e7/k/1e6] One full cycle needs two toggles.
- [any] $10^7/(2k)$.
:::
:::

::: part
answer: 1e7/(2*k)/12500
tolerance: 0.5%

### How many times faster than MicroPython's 12.5 kHz is that?

::: misses
- [any] The ratio.
:::
:::
:::

::: explain
## Why does a register appear in C as `*(volatile uint32_t *)0x40000010`, and what does each part do?

::: model
The number 0x40000010 is the register's address from the datasheet. Casting it to `uint32_t *` turns it into a pointer to a 32-bit unsigned value, matching the register's width, so loads and stores through it move whole 32-bit words. The leading `*` dereferences the pointer, so the whole expression behaves like a variable: assigning to it stores to the register and reading it loads from the register. `volatile` tells the compiler that this location can change, or has effects, outside the program's view, so it must perform every read and write exactly as written instead of caching the value in a register or removing writes that look redundant.
:::
:::

::: practice

::: check
given: t = 2 | 50; k = 5 | 6
answer: t*10000/k
tolerance: 0.5%

## Passes of a {k}-cycle loop in {t} ms?

::: misses
- [any] $t \times 10^4/k$.
:::
:::

::: check
given: k = 4 | 5 | 6 | 8 | 10 | 12 | 20
answer: 10000/(2*k)
unit: kHz
tolerance: 0.5%

## Toggle frequency with {k} cycles per pass?

::: misses
- [any] $10\text{ MHz}/(2k)$.
:::
:::

::: check
given: a = 1 | 4; b = 6 | 15
base: 16
answer: 2^a + 2^b

## Mask for P{a} and P{b}, in hex?

::: misses
- [any] Set bits {a} and {b}.
:::
:::
:::
