Try Embedded

UART

Baud rate, framing, errors, flow control and DMA reception.

The oldest serial port is still everywhere

A UART (universal asynchronous receiver-transmitter) sends bytes over a single wire in each direction with no shared clock. It is the debug console on nearly every board, and the interface to GPS modules, cellular and Wi-Fi modems, Bluetooth modules, RS-232 and RS-485 links.

  • TX of one side connects to RX of the other, and vice versa, plus a common ground.
  • Logic levels are the MCU's (3.3 V). RS-232 uses ±3 to ±15 V and needs a transceiver; RS-485 is differential and needs one too.

The frame

With no clock line, both sides must agree in advance on the baud rate and the frame format, written like 115200 8N1:

idle (high) | start (0) | D0 D1 D2 D3 D4 D5 D6 D7 | [parity] | stop (1) | idle
  • Start bit: the falling edge tells the receiver a byte begins; it then samples each bit in the middle of its period.
  • Data bits: usually 8, least significant bit first.
  • Parity: optional even or odd parity bit; detects single-bit errors.
  • Stop bit(s): 1 (or 2), high; guarantees a falling edge for the next start bit.

So 8N1 costs 10 bit times per byte: 115200 baud carries 11520 bytes per second.

#include <stdio.h>
#include <stdint.h>

/* Print the line level for each bit time of one 8N1 frame. */
int main(void) {
  uint8_t byte = 'A';                               /* 0x41 = 0100 0001 */
  printf("byte 0x%02X on the wire: ", byte);
  printf("1 | 0 |");                                /* idle, start bit */
  for (int i = 0; i < 8; i++) printf(" %d", (byte >> i) & 1);   /* LSB first */
  printf(" | 1 | 1\n");                             /* stop bit, idle */

  uint32_t baud = 115200;
  printf("bit time = %.2f us, byte time = %.2f us\n", 1e6 / baud, 10 * 1e6 / baud);
  return 0;
}

Baud rate accuracy

The receiver resynchronises only on the start bit's falling edge, so timing error accumulates over the frame. By the middle of the stop bit (9.5 bit times later) the sampling point must still be inside the bit. That allows roughly ±4% total mismatch in theory; practical guidance is to keep each side within about ±2%.

Sources of error:

  • The baud divisor. The UART divides its clock; the result is rarely exact. 115200 from 16 MHz with a 16× oversampling divisor of 8.6875 is fine on UARTs with fractional dividers, but an integer-only divider gives 8 or 9, errors of +8.5% or −3.5%.
  • The clock source. An internal RC oscillator at ±1% plus temperature drift can be marginal at high baud rates. Use a crystal for reliability, or a lower baud rate.

Errors the hardware reports

FlagMeaningTypical cause
Framing error (FE)Stop bit was 0Baud mismatch, noise, or a break
Parity error (PE)Parity check failedNoise, wrong parity setting
Noise flag (NF)Samples within a bit disagreedNoise on the line
Overrun (ORE)A new byte arrived before the last was readSoftware too slow: interrupts disabled too long, no DMA

An overrun is a software bug in almost every case. On many MCUs an overrun also stops reception until the flag is cleared, so a driver that never clears it goes deaf forever.

Receiving reliably

A byte arrives every 87 µs at 115200 baud, regardless of what the CPU is doing. Options, in order of robustness:

  1. Polling: only for trivial cases; any delay drops bytes.
  2. Interrupt per byte into a ring buffer: the ISR reads the data register and stores it; the main loop consumes. Fine up to moderate rates, if no long critical sections exist.
  3. DMA in circular mode + idle-line interrupt: the hardware stores every byte; the CPU wakes when the line goes idle or the buffer half fills. The best option for modems and high baud rates.

Then split the byte stream into messages in software: by newline for text protocols, by length fields or delimiters (with COBS or SLIP encoding) for binary ones, always with a timeout and a maximum length.

Flow control

When the receiver may not keep up (a modem with a small buffer, a PC that pauses), flow control stops the sender:

  • Hardware (RTS/CTS): two extra lines. A receiver deasserts RTS when its buffer is nearly full; the sender checks CTS before each byte. Reliable and immediate; supported in hardware by most UARTs.
  • Software (XON/XOFF): special bytes 0x11 and 0x13 sent in-band. Only usable with text data, and slower to react.

RS-485

RS-485 is a differential, multi-drop version: one twisted pair, up to 32 standard loads, up to about 1200 m. It is half duplex, so a driver-enable pin must turn on the transmitter only while sending and release it immediately after the last stop bit (many UARTs drive DE automatically). Modbus RTU runs on it.

Pitfall: Turning off the RS-485 driver when the "transmit buffer empty" flag sets cuts off the last byte, which is still being shifted out. Wait for "transmission complete" (TC), which sets after the stop bit.

Interview question: Your UART receives garbage characters. How do you debug it?

Answer: Check the baud rate and frame format on both sides first, since garbage with framing errors is classically a baud mismatch; measure a bit time on a scope or logic analyser and compare (1/baud). Check the clock configuration feeding the UART (wrong APB clock, internal RC drift) and the divisor error. Check TX and RX are crossed, grounds are common and logic levels match (3.3 V versus 5 V versus RS-232). Look at the error flags: framing errors suggest timing, overruns suggest software too slow.

Interview question: How would you design UART reception for a cellular modem at 921600 baud?

Answer: A byte arrives about every 11 µs, so per-byte interrupts are risky. Use DMA in circular mode into a large ring buffer, plus the idle-line interrupt and DMA half and full transfer interrupts; in each, compute the write position from the DMA counter and hand new bytes to a parser task. Enable RTS/CTS hardware flow control so the modem pauses if the buffer fills, use a crystal-based clock for baud accuracy, and handle overrun and framing errors by clearing the flags and counting them.

Build it: the tracker's service console

This is step 1 of the module project, an e-scooter tracker box. A technician plugs a USB-serial cable into the box's service port to check it and change its settings, so the first job is a console on the UART.

Lab: A service console on the UART

The service port is USART2, at 115200 baud from a 16 MHz peripheral clock. The technician types commands that end with Enter. Depending on the terminal program, Enter sends \r\n or just \n.

  • console_init() sets the baud rate (BRR = clock / baud, rounded to the nearest whole number), then enables the UART, its transmitter and its receiver in CR1.
  • console_write(s) sends a string. Before each byte, wait for TXE: writing DR while the previous byte is still going out loses it.
  • console_readline(buf, size) waits for bytes (RXNE) and collects one line. It stops at \n, ignores \r, and stores at most size - 1 characters followed by '\0'. A line longer than that is cut short, and the rest of it is thrown away up to its \n, never written past the end of buf. It returns the number of characters stored.

Every byte sent shows up in the output, such as usart2: tx 'O'. A check's typed input arrives on the receiver one byte at a time, at the speed of the wire.

Going deeper

Interview question: How would you design a field technician's serial console for a greenhouse controller?

Answer: A line-based protocol with simple commands, read without blocking into a bounded buffer, with strict parsing that rejects anything malformed or out of range and changes nothing on error. Protect dangerous commands (factory reset, pump test) behind a confirmation or a service mode, and log what was changed.

Interview question: What is a break condition on a UART line, and what is it used for?

Answer: A break is the line held at the low (space) level for longer than a full character frame. Receivers see it as a framing error with all zero data, so it cannot be confused with normal data. It is used as a reset or attention signal, to mark the start of a frame in LIN and DMX512, and some bootloaders use it to trigger a mode change.

Interview question: How do you detect the end of a variable-length UART message without a delimiter?

Answer: Use an idle-line detection interrupt or a receiver timeout feature: the UART signals when the line has been idle for one (or a configured number of) character times after data, which marks the end of a burst. Combined with DMA reception this handles messages of any length. Modbus RTU uses a 3.5-character silence for exactly this.

Explain it: In your own words, explain why two UARTs with slightly different clocks can still communicate.

Answer: The receiver resynchronises at the start of every character on the falling edge of the start bit, then samples each following bit in the middle of where it expects it to be. Timing error therefore only accumulates over one character of about ten bits, not over the whole message. As long as the combined clock mismatch keeps the last sample, in the stop bit, within the bit period, roughly a few percent in total, every bit is read correctly and the next start bit resets the timing.