---
title: Serial communication and the UART
heading: Bytes, one bit at a time, on a single wire
eyebrow: C12 · Lesson 28 · Serial communication and the UART
xp: 40
---

::: hook
The oldest and most common way for a microcontroller to talk is the **UART**: one wire out, one wire in, no clock, and both ends agreeing in advance on how fast bits go by. It carries debug messages to a terminal, commands from a computer, and readings from GPS modules, modems and sensors. Each byte travels as a **frame**: a start bit, eight data bits, and a stop bit. Because there's no shared clock, the receiver times each bit from the start bit's edge, so both ends' baud rates must match to within a few percent.
:::

::: play
- The program sends a greeting to the terminal, then echoes back anything typed. The terminal types "hi" at 2 ms.
- Zoom in on the first byte of TX: it idles high, drops for the start bit, then sends 'H' (0x48) least significant bit first, then a high stop bit. Each bit lasts 8.7 µs at 115,200 baud.
- Change `BAUD` to 9600 and run again: the same text takes twelve times as long, and its frames stretch across the timeline.
:::
:::

```sim board
lang: c
attach: terminal | send "hi" at 0.002 s
scope: TX, RX | 0..0.4 ms
run: 6 ms
code:
#include "board.h"

#define BAUD 115200

void putc(char c) {
    while (UART_STATUS & UART_TX_FULL) ;   // wait for room
    UART_DATA = c;
}

void puts(const char *s) {
    while (*s) putc(*s++);
}

int main(void) {
    UART_BAUDDIV = F_CPU / BAUD;          // clock cycles per bit
    puts("Hello, terminal\n");
    while (1) {
        if (UART_STATUS & UART_RX_READY)  // a byte arrived
            putc(UART_DATA);              // send it back
    }
}
```

::: predict
## At 115,200 baud with 8 data bits and one stop bit, how many bytes per second can a UART send at most?

- [ ] 115,200
- [ ] 14,400
- [x] 11,520
- [ ] 921,600

::: reveal
11,520: every byte travels as 10 bits (a start bit, 8 data bits, a stop bit), so the byte rate is the baud rate divided by 10. The start and stop bits are the price of not sharing a clock.
:::
:::

::: nameit
## The frame

The line idles at 1. A frame is:

1. a **start bit**, 0: its falling edge tells the receiver a byte is coming;
2. eight **data bits**, least significant first;
3. a **stop bit**, 1, returning the line to idle.

Each bit lasts $1/\text{baud}$; a frame lasts $10/\text{baud}$. Common rates: 9600, 115,200 and up to a few megabaud. Some links add a parity bit or a second stop bit.

## Matching rates

The receiver samples each bit near its middle, timing from the start bit's edge. By the last bit it's nine and a half bit-times in, so a rate mismatch of about 5% (between the two ends combined) shifts the sample out of its bit. Keep each end within about 2%. This board divides its clock:

$$\text{BAUDDIV} = \frac{f_\text{clk}}{\text{baud}}, \qquad \text{error} = \frac{f_\text{clk}/\text{BAUDDIV} - \text{baud}}{\text{baud}}$$

## Using it

| | |
|---|---|
| C | wait while `UART_STATUS & UART_TX_FULL`, then write `UART_DATA`; when `UART_STATUS & UART_RX_READY`, read `UART_DATA` |
| MicroPython | `u = UART(0, 115200)`; `u.write('text')`, `u.any()`, `u.read(n)`, `u.readline()` |

The transmitter holds one byte waiting while another shifts out. The receiver holds just one received byte: if another arrives before the program reads it, the first is lost and `UART_OVERRUN` is set (lesson 29 fixes that with interrupts and a buffer).

## Levels

This board's pins use 3.3 V logic ("TTL serial"). A computer connects through a USB-to-serial adapter; the old RS-232 standard uses ±3 to ±15 V and an inverting driver chip.
:::

::: example
## Draw the frame for 'A' (0x41).

::: solution
1. **Write it in binary.**
   $$\text{0x41} = 0100\ 0001$$
2. **Send it LSB first.** The data bits are 1, 0, 0, 0, 0, 0, 1, 0.
3. **Frame it.** On the wire: idle 1, start 0, then 1 0 0 0 0 0 1 0, then stop 1.
4. **Time it.** That's ten bit-times of 8.68 µs each at 115,200 baud.

**Answer:** idle 1, start 0, data 1 0 0 0 0 0 1 0, stop 1: ten bit-times of 8.68 µs.
:::
:::

::: example
## What BAUDDIV gives 115,200 baud, and how far off is it?

::: solution
1. **Divide the clock by the baud rate.**
   $$\frac{10^7}{115\,200} = 86.8$$
   so BAUDDIV = 87.
2. **The rate it gives.**
   $$\frac{10^7}{87} = 114\,943\ \text{baud}$$
3. **How far off.** That's 0.22% slow, comfortably inside the 2% budget.

**Answer:** BAUDDIV = 87, which gives 114,943 baud, 0.22% slow.
:::
:::

::: example
## How many bytes per second does a 115,200-baud link carry with 8N1 framing, and with 8N2 (two stop bits)?

::: solution
1. **8N1.** Each byte is 10 bit-times:
   $$\frac{115\,200}{10} = 11\,520\ \text{bytes/s}$$
2. **8N2.** Each byte is 11:
   $$\frac{115\,200}{11} = 10\,473\ \text{bytes/s}$$
   9% less.
3. **When it's worth it.** The extra stop bit only helps receivers that need more time between bytes.

**Answer:** 11,520 bytes/s with 8N1 and 10,473 bytes/s with 8N2.
:::
:::

::: check
given: b = 9600 | 57600 | 115200 | 1000000
answer: 1e6/b
unit: µs
tolerance: 0.5%

## How long is one bit at {b} baud?

::: right
Right. $1/\text{baud}$ = {answer} µs.
:::

::: misses
- [any] Not yet. One over the baud rate.
:::
:::

::: check
given: b = 9600 | 115200; n = 1 | 12 | 100
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

## How long does it take to send {n} bytes at {b} baud, back to back?

::: right
Right. 10 bits per byte: {answer} ms.
:::

::: misses
- [n*8/b*1000] Count the start and stop bits: 10 bits per byte.
- [any] Not yet. Bytes × 10 / baud.
:::
:::

::: check
given: b = 9600 | 38400 | 115200 | 230400
answer: round(1e7/b)
tolerance: 0

## What BAUDDIV comes closest to {b} baud on the 10 MHz board?

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

::: misses
- [any] Not yet. $f_\text{clk}/\text{baud}$, rounded.
:::
:::

::: check
given: b = 115200 | 230400 | 460800
answer: 100*(1e7/round(1e7/b) - b)/b
unit: %
tolerance: 1%

## With BAUDDIV rounded, how far off {b} baud is the board, in percent (negative if slow)?

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

::: misses
- [any] Not yet. Compare $f_\text{clk}/\text{BAUDDIV}$ with the target.
:::
:::

::: check
given: v = 0x41 | 0x4B | 0x0D | 0x31
base: 2
answer: (floor(v/1) - 2*floor(v/2))*128 + (floor(v/2) - 2*floor(v/4))*64 + (floor(v/4) - 2*floor(v/8))*32 + (floor(v/8) - 2*floor(v/16))*16 + (floor(v/16) - 2*floor(v/32))*8 + (floor(v/32) - 2*floor(v/64))*4 + (floor(v/64) - 2*floor(v/128))*2 + (floor(v/128) - 2*floor(v/256))*1

## The byte {v:hex2} is sent. Write its eight data bits in the order they appear on the wire, first bit on the left, as a binary number.

::: right
Right. Least significant bit first: {answer:bin8}.
:::

::: misses
- [v] That's the byte as written, most significant bit first; a UART sends the least significant bit first.
- [any] Not yet. Start with bit 0 of the byte and end with bit 7.
:::
:::

::: check
given: b = 1200 | 2400 | 4800 | 9600 | 19200 | 38400 | 57600 | 115200
answer: b/10
tolerance: 0.5%

## What's the most bytes per second a UART can send at {b} baud, with 8 data bits and one stop bit?

::: right
Right. {answer} bytes per second.
:::

::: misses
- [b/8] Each byte is 10 bits on the wire.
- [any] Not yet. Baud ÷ 10.
:::
:::

::: check
kind: choice

## A terminal shows garbled characters from a board. What's the most likely cause?

- [ ] The board's TX pin needs a pull-up
- [x] The two ends are set to different baud rates
- [ ] The data bits are being sent least significant first
- [ ] The stop bit is 1

::: misses
- [1] TX idles high on its own; that's not a garbling cause.
- [3] That's the standard; both ends expect it.
- [4] Every UART's stop bit is 1.
:::
:::

::: check
kind: c
given: N = 42 | 307 | 4095
attach: terminal
run: 0.01
expect: terminal = "N={N}\n"

## Send the text `N=` followed by the number `N` ({N}) in decimal and a newline, at 115,200 baud. (Convert the number to digits yourself.)

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

int main(void) {
    UART_BAUDDIV = 87;
    UART_DATA = 'N';
    return 0;
}
```

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

void putc(char c) {
    while (UART_STATUS & UART_TX_FULL) ;
    UART_DATA = c;
}

void putnum(uint32_t n) {
    char digits[10];
    int k = 0;
    do { digits[k++] = '0' + n % 10; n /= 10; } while (n);
    while (k) putc(digits[--k]);
}

int main(void) {
    UART_BAUDDIV = 87;
    putc('N'); putc('=');
    putnum(N);
    putc('\n');
    while (!(UART_STATUS & UART_TX_IDLE)) ;
    return 0;
}
```

::: right
Right. Digits come out least significant first from `% 10`, so they're stored and sent in reverse.
:::
:::

::: check
kind: micropython
attach: terminal | send "hello board\n" at 0.002 s
run: 0.05
expect: terminal = "HELLO BOARD\n"

## Wait for a line from the terminal and send it back in capitals.

```micropython starter
from machine import UART

u = UART(0, 115200)
u.write('?\n')
```

```micropython solution
from machine import UART
import time

u = UART(0, 115200)
line = None
while line is None:
    line = u.readline()
    time.sleep_ms(1)
u.write(line.upper())
```

::: right
Right. `readline` returns None until a whole line has arrived.
:::
:::

::: check
kind: parts
given: b = 9600 | 57600 | 115200 | 921600

## The UART runs at $10^7/\text{BAUDDIV}$ baud; {b} baud is wanted.

::: part
answer: round(1e7/b)
tolerance: 0

### What BAUDDIV?

::: misses
- [any] $10^7/b$, rounded.
:::
:::

::: part
answer: (1e7/round(1e7/b) - b)/b*100
unit: %
tolerance: 1%

### How far off is the actual rate?

::: misses
- [any] (actual − wanted)/wanted.
:::
:::
:::

::: check
kind: parts
given: b = 9600 | 115200 | 1000000; s = 1 | 2

## A UART at {b} baud uses 8 data bits, no parity and {s} stop bit(s).

::: part
answer: (9 + s)/b*1e6
unit: µs
tolerance: 0.5%

### How long does one byte take?

::: misses
- [any] Start + 8 data + stop bits.
:::
:::

::: part
answer: b/(9 + s)
tolerance: 0.5%

### How many bytes per second?

::: misses
- [any] Baud over bits per byte.
:::
:::
:::

::: explain
## Why does a UART frame need a start bit and a stop bit when the data is only eight bits?

::: model
There's no clock wire, so the receiver must find where each byte begins and time its bits itself. The idle line sits at 1, so a start bit of 0 makes a falling edge the receiver can't miss; it measures every bit from that edge, sampling each in its middle. The stop bit of 1 returns the line to idle, guaranteeing the next start bit makes a fresh falling edge, so the receiver resynchronizes on every byte. That resynchronization is why small baud-rate differences don't accumulate: they only have to stay within half a bit over the ten bits of one frame.
:::
:::

::: practice

::: check
given: b = 9600 | 19200 | 38400 | 115200 | 230400 | 460800 | 921600
answer: 1e6/b
unit: µs
tolerance: 0.5%

## Bit time at {b} baud?

::: misses
- [any] $1/\text{baud}$.
:::
:::

::: check
given: b = 9600 | 57600 | 115200; n = 10 | 25 | 64 | 100 | 250 | 1000
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

## Time for {n} bytes at {b} baud?

::: misses
- [any] Bytes × 10 / baud.
:::
:::

::: check
given: b = 9600 | 19200 | 31250 | 38400 | 57600 | 115200 | 250000 | 1000000
answer: round(1e7/b)
tolerance: 0

## BAUDDIV for {b} baud?

::: misses
- [any] $f_\text{clk}/\text{baud}$.
:::
:::
:::
