UART in firmware: baud rate and ring buffers
About this lesson
Write the receive side of a UART driver for an Arduino Uno R3 (ATmega328P, 16 MHz). Set the baud rate by dividing the clock (UBRR0 = 207 gives 9,615 baud), follow one byte's bits along the RX wire into UDR0, then let an interrupt move each byte into an 8-slot ring buffer that loop() empties when it has time. Watch head and tail chase each other round the ring, and see what happens when loop() stops reading for 100 ms. The Hardware lesson “Serial buses: UART, I2C and SPI” explains the wires and the frame; the DSA lesson “Ring buffers and deques under the hood” covers the data structure. Here you write the driver.
One wire, no clock
UART sends bytes over one wire, the sender's TX to the receiver's RX, plus ground. There is no clock wire, so both ends must agree on a speed: the baud rate. On an Uno the PC reaches RX pin 0 through a USB chip.
UART universal asynchronous receiver-transmitter wires TX -> RX, plus a shared ground clock none on the wire: both ends agree a baud rate Uno PC -> USB chip (ATmega16U2) -> RX pin 0 of the ATmega328P the Hardware lesson "Serial buses: UART, I2C and SPI" covers the wires
Read the lesson step by step
One wire, no clock
UART sends bytes over one wire, the sender's TX to the receiver's RX, plus ground. There is no clock wire, so both ends must agree on a speed: the baud rate. On an Uno the PC reaches RX pin 0 through a USB chip.
UART universal asynchronous receiver-transmitter wires TX -> RX, plus a shared ground clock none on the wire: both ends agree a baud rate Uno PC -> USB chip (ATmega16U2) -> RX pin 0 of the ATmega328P the Hardware lesson "Serial buses: UART, I2C and SPI" covers the wiresSet the baud rate
The UART divides the 16 MHz clock. In double-speed mode the datasheet's rule is 16,000,000 ÷ (8 × (UBRR0 + 1)). UBRR0 = 207 gives 9,615 baud, 0.2% fast of 9,600: inside the 1.5% the receiver tolerates.
line 1 UBRR0 = 207; with U2X0 = 1 (double speed) rule BAUD = f / (8 * (UBRR0 + 1)) 16,000,000 / (8 * 208) = 9615.4 error +0.16% (datasheet table: 0.2%) limit about ±1.5% for 8 data bits, double speed Arduino Serial.begin(9600) picks the same 207A byte arrives: 'h'
You type 'h'. It travels as 0x68 in a frame of 10 bits: a 0 start bit, eight data bits lowest first, then a 1 stop bit. Each bit lasts 1/9,615 s, so a byte takes 1.04 ms. The UART shifts it into UDR0.
'h' = 0x68 = 01101000 frame 0 0 0 0 1 0 1 1 0 1 start, d0 .. d7 (lowest first), stop bit 104 µs byte 10 bits = 1.04 ms speed about 962 bytes a secondThe interrupt takes it
Once the stop bit is in, the UART sets a flag and the RX interrupt fires: loop() pauses and the ISR runs. It reads UDR0 straight away. The chip holds only 2 received bytes, so the ISR must move each one out fast.
RXC0 flag set -> ISR(USART_RX_vect) runs line 3 uint8_t c = UDR0; c = 'h' reading UDR0 empties it and clears RXC0 hardware buffer: 2 bytes ("a two level FIFO") at 9,615 baud a new byte can land every 1.04 msInto the ring buffer
The ISR works out n = (head + 1) % 8 = 1. That is not tail (0), so there is room: buf[0] = 'h' and head becomes 1. head is where the next byte goes; tail is the next one to read.
ring buf[8] in SRAM, head = 0, tail = 0 (empty) line 4 n = (0 + 1) % 8 = 1 line 5 1 == tail (0)? no, so there is room line 6 buf[0] = 'h'; head = 1 head where the ISR writes next tail where loop() reads nextMore bytes, same ISR
'i' and the newline arrive 1.04 ms apart, and each runs the same ISR: buf[1] = 'i', buf[2] = '\n', head = 3. Bytes waiting = (8 + head − tail) % 8 = 3, the sum Arduino's Serial.available() does.
'i' -> buf[1], head = 2 '\n' -> buf[2], head = 3 waiting (8 + 3 - 0) % 8 = 3 loop() has not run a single line for these bytesloop() takes them out
In loop(), head != tail means a byte is waiting. c = buf[tail] gives 'h' and tail moves on. Two more reads give 'i' and '\n'; now head == tail: empty. Only the ISR writes head and only loop() writes tail, so they never clash.
line 7 head (3) != tail (0): a byte is waiting line 8 c = buf[0] = 'h'; tail = 1 c = buf[1] = 'i'; tail = 2 c = buf[2] = '\n'; tail = 3 head == tail == 3: empty ISR writes head only, loop() writes tail onlyRound and round
Next comes 'hello\n' while loop() reads. After slot 7, (7 + 1) % 8 = 0: head wraps back to slot 0, then 1. loop() has read 'h', 'e', 'l', so tail is 6. Waiting: (8 + 1 − 6) % 8 = 3.
'hello\n' -> slots 3, 4, 5, 6, 7, then 0 line 4 (7 + 1) % 8 = 0: the index wraps head = 1, tail = 6 waiting (8 + 1 - 6) % 8 = 3: 'l' 'o' '\n' no bytes move: only the two indexes go roundBug: the ring overflows
Now loop() sits in delay(100); about 96 bytes can arrive meanwhile. A 20-byte line comes: 4 free slots fill, then (head + 1) % 8 == tail, so the ISR drops the other 16 and counts them in lost.
loop() delay(100): no reads for 100 ms arrive 100 ms / 1.04 ms = about 96 bytes ring holds 7 at most (one slot stays empty) line "the quick brown fox\n" (20 bytes) kept "the " dropped 16 line 5 n == tail -> lost++ (lost = 16)Fix: read often, size it
Read often, and size the ring for the longest gap between reads. A byte lands every 1.04 ms, so if loop() can be away 20 ms, about 20 arrive: use 32 slots. Arduino's Serial uses this same ring with 64 bytes on the Uno.
gap 20 ms -> 20 / 1.04 = about 20 bytes need 20 + 1 slots -> 32 (a power of two) Arduino Serial on the Uno: 64-byte ring, 63 usable that is 66 ms of 9,600-baud text lost > 0 tells you it happened: check it while testing
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01An ATmega328P runs at 16 MHz in double-speed mode (U2X0 = 1). Which UBRR0 value gives 9600 baud most closely?
The datasheet's rule is UBRR0 = 16,000,000 ÷ (8 × 9600) − 1 = 207.3, so 207, giving 9,615 baud (0.2% fast). 103 is the value for normal speed (U2X0 = 0); 16 is for 115200 baud.
02Why does the driver move each received byte into a ring buffer inside the RX interrupt?
At 9,615 baud a new byte can arrive every 1.04 ms and the receive buffer is only a two-level FIFO. The ISR runs as soon as each byte is in, so nothing is overwritten while loop() is busy.
03An 8-slot ring has head = 1 and tail = 6. How many bytes are waiting?
Waiting = (8 + head − tail) % 8 = (8 + 1 − 6) % 8 = 3: slots 6, 7 and 0. The writer has wrapped past slot 7, so head is smaller than tail.
04Why can an 8-slot ring buffer hold at most 7 bytes?
If all slots could fill, head would catch up to tail and look exactly like an empty ring. Keeping one gap makes full and empty different states without a separate count.
05loop() sometimes spends 20 ms without reading, at 9600 baud (8N1). What is the smallest power-of-two ring that loses nothing?
A byte takes 1.04 ms, so about 20 bytes arrive in 20 ms. The ring needs that many plus the one empty slot, so 16 is too small and 32 is the next power of two.
Glossary
- UART
- Universal asynchronous receiver-transmitter: sends bytes one bit at a time on a TX wire to an RX wire, with no clock wire.
- Baud rate
- Bits per second on a UART line. Both ends must use (nearly) the same rate, because there is no shared clock.
- UBRR0
- The ATmega328P's baud rate register. In double-speed mode the baud rate is the clock ÷ (8 × (UBRR0 + 1)).
- UDR0
- The ATmega328P's UART data register. Reading it takes the next received byte and clears the receive-complete flag.
- Interrupt service routine (ISR)
- A short function the hardware runs as soon as an event happens, such as a byte arriving, pausing the main loop for a moment.
- Ring buffer
- A fixed array used as a queue: a write index (head) and a read index (tail) move forward and wrap from the last slot back to the first.
- Overflow
- Data arriving when the buffer is full. A ring buffer driver drops the new byte and can count it, as the lost counter does here.
Notes and sources
- The card shows the core lines only. The full sketch also turns on double speed (U2X0), the receiver and the RX interrupt in UCSR0B, declares buf, head, tail and lost as volatile, and wraps the read in uart_read(), which returns -1 when the ring is empty. Do not use Serial in the same sketch: the Arduino core's Serial already defines this ISR.
- One slot always stays empty, so 8 slots hold at most 7 bytes: that way head == tail can only mean empty. The drawing blanks a slot once it is read; in real memory the old byte stays until it is overwritten. A power-of-two size lets the compiler do % 8 as a cheap bit mask.
- If an ISR returned without reading UDR0, the RXC0 flag would stay set and the interrupt would fire again at once. head and tail are single bytes, so each is read and written in one go on this 8-bit chip; the lesson "volatile and sharing data with an ISR" explains why they must be volatile.
- The PC side runs from its own clock, so the two ends never match exactly. The datasheet recommends keeping the receiver within about ±1.5% in double-speed mode with 8 data bits; 0.16% is well inside that.
- The drawing gives the chip six legs and runs the RX trace to the leg below UDR0. The real ATmega328P on the Uno has 28 pins, and the Uno's pin 0 is the chip's RXD pin (PD0).
- Other chips use the same idea: on an ESP32, ESP-IDF's uart_driver_install() takes the size of the receive ring buffer, which must be bigger than the UART's hardware FIFO.
- Microchip ATmega48A/PA/88A/PA/168A/PA/328/P datasheet (DS40002061B), ch. 20 USART0
- Arduino AVR core: HardwareSerial.cpp (begin, read, available)
- Arduino AVR core: HardwareSerial_private.h (the receive interrupt)
- Arduino AVR core: HardwareSerial.h (SERIAL_RX_BUFFER_SIZE)
- Arduino language reference: Serial (source)
- Arduino language reference: Serial.begin() (source)
- Arduino UNO R3 product datasheet (A000066)
- J. W. Valvano, Embedded Systems: Shape the World, ch. 11 Serial Interfacing (UT Austin)
- Espressif ESP-IDF: UART driver (ESP32)
- E. A. Lee and S. A. Seshia, Introduction to Embedded Systems, 2nd ed. (MIT Press, 2017)
Quiz Unlocks after the last step.