C1229 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C12 · Lesson 29 · Ring buffers and interrupt-driven serial

Never losing a byte while the program is busy

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.

  • 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.

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?

Name it

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 232. 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

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.

Worked example

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

Show the solution
  1. Bytes that can arrive. At 11,520 bytes a second: 11520×0.012=138bytes
  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.

Worked example

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

Show the solution
  1. Cycles per second. 25×11520=288000
  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.

Worked example

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

Show the solution
  1. Subtract modulo 64. (head−tail)mod64=(5−60)mod64=9 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

A ring buffer's head counter is 77 and its tail counter is 970. How many bytes are waiting?

Check

In a 16-slot ring buffer, which slot does counter 100 use?

Check

At 115200 baud, how often does a new byte arrive in a continuous stream?

Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.

Check

The main program may be busy for up to 2 ms while bytes stream in at 9600 baud. How many bytes must the buffer hold, at least?

Check

A receive ISR takes 40 cycles per byte. At 115200 baud, what share of the processor does it use?

Check

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

Check

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 (10), get B (3), 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 on the course's RISC-V board (10 MHz, no floating point). #include "board.h" for the registers; print(x) shows a number. Tab indents; press Esc and then Tab to move on.

Check

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 on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.

Check

A program may be away for 12 ms while bytes arrive at 9600 baud.

(a)

How many bytes can arrive meanwhile?

(b)

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

Check

A ring buffer of 64 bytes has head = 3 and tail = 200.

(a)

How many bytes are waiting?

(b)

How many more can it take?

Explain why

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

Practice

Keep practicing

11 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.