---
title: Ring buffers and interrupt-driven serial
heading: Never losing a byte while the program is busy
eyebrow: C12 · Lesson 29 · Ring buffers and interrupt-driven serial
xp: 40
---

::: hook
At 115,200 baud a new byte arrives every 87 µs, and the UART holds only one. A program that checks for bytes between other jobs has to come back within 87 µs every time, or the next byte overwrites the last. Real programs can't promise that. The standard fix is an interrupt that runs the moment each byte arrives and moves it into a **ring buffer**, a fixed array used as a queue that wraps around; the main program takes bytes out whenever it gets to them. The same pattern carries data between any interrupt and any main loop.
:::

::: play
- The terminal sends a 40-character line at 1 ms. The program counts the bytes it receives over 30 ms, but each time there's nothing waiting, it spends 1 ms on other work.
- As written (`USE_IRQ 0`) it polls: it prints 4. Most bytes arrived while it was busy, and each overwrote the one before.
- Set `USE_IRQ` to 1 and run again: the UART's receive interrupt puts every byte in the ring buffer the moment it arrives, and the program counts all 40.
:::
:::

```sim board
lang: c
attach: terminal | send "The quick brown fox jumps over the dog.\n" at 0.001 s
scope: RX | 0..6 ms
run: 40 ms
show: debug
code:
#include "board.h"

#define USE_IRQ 0
#define SIZE 64                      // a power of two

volatile uint8_t buf[SIZE];
volatile uint32_t head = 0, tail = 0; // head: next to write; tail: next to read

void __attribute__((interrupt)) on_uart(void) {
    while (UART_STATUS & UART_RX_READY) {
        buf[head & (SIZE - 1)] = UART_DATA;
        head++;
    }
}

int get(void) {                       // a byte, or -1 if there's none
    if (USE_IRQ) {
        if (tail == head) return -1;
        return buf[tail++ & (SIZE - 1)];
    }
    if (UART_STATUS & UART_RX_READY) return UART_DATA;
    return -1;
}

void slow_work(void) {                // 1 ms of something else
    uint32_t t = SYS_CYCLES;
    while (SYS_CYCLES - t < 10000) ;
}

int main(void) {
    UART_BAUDDIV = 87;
    if (USE_IRQ) {
        set_trap_handler(on_uart);
        UART_CTRL = UART_RX_IRQ;
        enable_external_interrupt();
        enable_interrupts();
    }
    int count = 0;
    uint32_t start = SYS_CYCLES;
    while (SYS_CYCLES - start < 300000) {   // 30 ms
        int c = get();
        if (c >= 0) count++;
        else slow_work();
    }
    print(count);
    return 0;
}
```

::: predict
## A ring buffer has 64 slots. Its write counter `head` is 1000 and its read counter `tail` is 970. How many bytes are waiting?

- [ ] 64
- [x] 30
- [ ] 1970
- [ ] It's corrupt, because head is past 64

::: reveal
30: the counters run freely and only their difference matters, $1000 - 970 = 30$. Each counter is turned into a slot by `& 63`, so it wraps around the array automatically; head can be any distance past tail up to 64.
:::
:::

::: nameit
## The ring buffer

An array of N slots (N a power of two) and two counters:

- the producer writes at slot `head & (N - 1)` and increments `head`;
- the consumer reads at slot `tail & (N - 1)` and increments `tail`;
- `head - tail` is the number of bytes waiting: 0 means empty, N means full.

With unsigned counters the subtraction stays right even when they wrap past $2^{32}$. Only the ISR changes `head` and only the main program changes `tail`, so neither needs to disable interrupts to read the other's counter (a single aligned 32-bit load is atomic). A producer that finds the buffer full must drop the byte, or the buffer must be bigger.

## Sizing it

If bytes arrive at rate r and the consumer can be away for up to T, the buffer must hold $rT$ bytes, plus margin. At 115,200 baud, r is 11,520 bytes per second, so a program that may be busy for 5 ms needs at least 58 slots: 64.

## The receive interrupt

```c
void __attribute__((interrupt)) on_uart(void) {
    while (UART_STATUS & UART_RX_READY) {
        buf[head & (SIZE - 1)] = UART_DATA;   // reading DATA clears READY
        head++;
    }
}
```

`UART_CTRL = UART_RX_IRQ` enables it. Transmitting works the same way in reverse: the main program fills a transmit ring buffer, and the "transmitter idle" interrupt feeds the UART from it. MicroPython's UART driver already buffers received bytes this way, which is why `u.any()` and `u.read()` don't lose data.
:::

::: example
## A program can be away for up to 12 ms. How big must its receive buffer be at 115,200 baud?

::: solution
1. **Bytes that can arrive.** At 11,520 bytes a second:
   $$11\,520 \times 0.012 = 138\ \text{bytes}$$
2. **Round up.** The next power of two is 256, which also leaves margin for a slower consumer.

**Answer:** at least 138 bytes, so 256.
:::
:::

::: example
## The ISR takes 25 cycles per byte. What share of the processor does receiving at full rate cost?

::: solution
1. **Cycles per second.**
   $$25 \times 11\,520 = 288\,000$$
2. **Share of the processor.** That's 2.9% of the 10 MHz processor: a small price for never losing a byte.

**Answer:** 2.9% of the processor.
:::
:::

::: example
## A 64-byte ring buffer has head = 5 and tail = 60. How many bytes are waiting?

::: solution
1. **Subtract modulo 64.**
   $$\begin{aligned} &(\text{head} - \text{tail}) \bmod 64 \\ &= (5 - 60) \bmod 64 \\ &= 9 \end{aligned}$$
   The writer has wrapped past the end.
2. **Do it in one instruction.** With a power-of-two size, `(head - tail) & 63` computes it in one instruction, which is why ring buffers are usually 2ⁿ long.

**Answer:** 9 bytes are waiting.
:::
:::

::: check
given: h = 1000 | 77 | 4100; t = 970 | 60 | 4090
answer: h - t
tolerance: 0

## A ring buffer's head counter is {h} and its tail counter is {t}. How many bytes are waiting?

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

::: misses
- [any] Not yet. head − tail.
:::
:::

::: check
given: c = 70 | 100 | 1023; N = 16 | 64
answer: c - N*floor(c/N)
tolerance: 0

## In a {N}-slot ring buffer, which slot does counter {c} use?

::: right
Right. `c & ({N} - 1)` = {answer}.
:::

::: misses
- [c] The counter keeps growing; the slot wraps at {N}.
- [any] Not yet. The counter modulo {N}.
:::
:::

::: check
given: b = 9600 | 115200 | 921600
answer: 10/b*1e6
unit: µs
tolerance: 0.5%

## At {b} baud, how often does a new byte arrive in a continuous stream?

::: right
Right. Every {answer} µs: a polling loop must look at least that often.
:::

::: misses
- [8/b*1e6] A byte is 10 bits on the wire.
- [any] Not yet. 10 bits per byte.
:::
:::

::: check
given: b = 9600 | 115200; T = 2 | 10 | 50
answer: b/10*T/1000
tolerance: 1%

## The main program may be busy for up to {T} ms while bytes stream in at {b} baud. How many bytes must the buffer hold, at least?

::: right
Right. $rT$ = {answer} bytes.
:::

::: misses
- [b*T/1000] Bytes, not bits: divide the baud rate by 10.
- [any] Not yet. Bytes per second times the time away.
:::
:::

::: check
given: c = 20 | 40 | 120; b = 115200 | 921600
answer: 100*c*b/10/1e7
unit: %
tolerance: 0.5%

## A receive ISR takes {c} cycles per byte. At {b} baud, what share of the processor does it use?

::: right
Right. {answer}%.
:::

::: misses
- [any] Not yet. Cycles per byte × bytes per second ÷ 10 MHz.
:::
:::

::: check
kind: choice

## Why can the main program read `head` (written by the ISR) without disabling interrupts?

- [ ] Because `head` is volatile
- [x] Because only the ISR writes it, and a 32-bit load reads it in one indivisible step
- [ ] Because the ISR is short
- [ ] Because ring buffers can't overflow

::: misses
- [1] Volatile makes the read happen; it doesn't make a multi-step update safe. Here there's no multi-step update to protect.
- [3] Shortness doesn't prevent it landing mid-sequence.
- [4] They can, when the consumer falls too far behind.
:::
:::

::: check
kind: c
given: A = 8 | 10 | 12; B = 3 | 7
run: 0.01
expect: print = A - B, A - B + 4, B + 1

## Write a 16-slot ring buffer of `uint8_t` with `void put(uint8_t v)` and `int get(void)` (−1 when empty). Put `A` bytes ({A}), get `B` ({B}), print how many are waiting; put 4 more and print again; then print the value of the next byte read, if the bytes put were 1, 2, 3, ... in order.

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

uint8_t buf[16];
uint32_t head = 0, tail = 0;

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

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

uint8_t buf[16];
uint32_t head = 0, tail = 0;

void put(uint8_t v) { buf[head++ & 15] = v; }
int get(void) { if (tail == head) return -1; return buf[tail++ & 15]; }

int main(void) {
    int next = 1;
    for (int i = 0; i < A; i++) put(next++);
    for (int i = 0; i < B; i++) get();
    print(head - tail);
    for (int i = 0; i < 4; i++) put(next++);
    print(head - tail);
    print(get());
    return 0;
}
```

::: right
Right. After {B} reads, the next byte out is number {B} + 1.
:::
:::

::: check
kind: micropython
attach: terminal | send "0123456789abcdefghij\n" at 0.001 s
run: 0.06
expect: print = 21

## Receive everything the terminal sends in the first 50 ms, while also spending 5 ms at a time on other work (`time.sleep_ms(5)` stands in for it), and print how many bytes arrived.

```micropython starter
from machine import UART
import time

u = UART(0, 115200)
count = 0
time.sleep_ms(50)
print(count)
```

```micropython solution
from machine import UART
import time

u = UART(0, 115200)
count = 0
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 50:
    data = u.read()
    if data:
        count += len(data)
    time.sleep_ms(5)
print(count)
```

::: right
Right. MicroPython's UART driver buffers bytes in the background, the way the play's ring buffer does, so reading every 5 ms loses nothing.
:::
:::

::: check
kind: parts
given: t = 5 | 12 | 50; b = 9600 | 115200

## A program may be away for {t} ms while bytes arrive at {b} baud.

::: part
answer: ceil(b/10*t/1000)
tolerance: 0

### How many bytes can arrive meanwhile?

::: misses
- [any] Bytes per second × time, rounded up.
:::
:::

::: part
answer: 2^ceil(log(ceil(b/10*t/1000) + 1)/log(2))
tolerance: 0

### What power-of-two buffer holds them (one slot stays empty)?

::: misses
- [any] The next power of two above that count.
:::
:::
:::

::: check
kind: parts
given: N = 16 | 64 | 256; h = 3 | 10; t = 12 | 200

## A ring buffer of {N} bytes has head = {h} and tail = {t}.

::: part
answer: h - t - N*floor((h - t)/N)
tolerance: 0

### How many bytes are waiting?

::: misses
- [any] $(h - t) \bmod N$.
:::
:::

::: part
answer: N - 1 - (h - t - N*floor((h - t)/N))
tolerance: 0

### How many more can it take?

::: misses
- [any] $N - 1$ less those waiting.
:::
:::
:::

::: explain
## Why does moving received bytes into a buffer from an interrupt stop them being lost, when polling the same UART doesn't?

::: model
The UART can hold only one received byte, so each byte has to be taken away before the next finishes arriving, 87 µs later at 115,200 baud. A polling loop only gets there when its other work allows, and any job longer than one byte-time lets bytes overwrite each other. The receive interrupt runs within microseconds of each byte's arrival, whatever the main program is doing, and moves it into the ring buffer, so the hardware's one-byte limit is never reached. The main program can then fall behind by as many bytes as the buffer holds and still catch up later without loss.
:::
:::

::: practice

::: check
given: h = 2049 | 515; t = 2030 | 500
answer: h - t
tolerance: 0

## Bytes waiting with head {h}, tail {t}?

::: misses
- [any] head − tail.
:::
:::

::: check
given: c = 300 | 777; N = 32 | 128
answer: c - N*floor(c/N)
tolerance: 0

## Slot for counter {c} in {N} slots?

::: misses
- [any] c mod {N}.
:::
:::

::: check
given: b = 57600 | 115200; T = 2 | 4 | 5 | 10 | 20 | 50
answer: b/10*T/1000
tolerance: 1%

## Buffer bytes for {T} ms away at {b} baud?

::: misses
- [any] $rT$.
:::
:::
:::
