Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Communication Buses

UART and Serial Communication

Understand UART frames, baud rates and error flags, calculate baud divisors, and write a byte-wise packet parser with a checksum in embedded C.

Microcontrollers rarely work alone. They talk to a PC console, a GPS module, a Bluetooth chip, a sensor, or another microcontroller. The simplest and oldest way is the UART (Universal Asynchronous Receiver/Transmitter): two wires, TX and RX, plus ground. It is the port behind printf debugging, AT-command modems, GPS NMEA sentences and countless bootloaders.

"Asynchronous" is the key word: there is no clock wire. Sender and receiver agree beforehand on the speed (the baud rate) and the frame format, and the receiver re-synchronizes on every byte using a start bit. This lesson explains the frame, the timing, the error flags, and then shows how to turn a raw byte stream into reliable packets.

The frame

When idle, a UART line sits at logic high. To send a byte, the transmitter pulls the line low for one bit time (the start bit), then sends the data bits least significant bit first, optionally a parity bit, and finally drives the line high for one or two stop bits. The most common setting is written 8N1: 8 data bits, no parity, 1 stop bit, so 10 bit times carry 8 bits of data.

flowchart LR
    I["Idle: high"] --> S["Start: low"]
    S --> D0["D0 (LSB)"]
    D0 --> D1["D1 ... D6"]
    D1 --> D7["D7 (MSB)"]
    D7 --> P["Parity (optional)"]
    P --> T["Stop: high"]
    T --> I2["Idle or next start"]

A UART frame. The falling edge of the start bit tells the receiver when to start sampling.

  • Baud rate is bits per second on the line (for UART it equals symbols per second). At 115,200 baud one bit lasts about 8.68 microseconds, and an 8N1 byte takes 86.8 microseconds, so the maximum throughput is about 11.5 kB/s.
  • Parity is a single check bit. With even parity it is chosen so the total number of 1 bits (data plus parity) is even. It catches any single flipped bit but not two.
  • Stop bits give the receiver time to finish the byte and guarantee the high-to-low edge needed for the next start bit.

The receiver detects the start edge, waits half a bit time to get to the middle of the start bit, and then samples every full bit time, at the center of each bit where the signal is most stable. Typical hardware oversamples 16 times per bit and takes the majority of three samples near the middle, which makes it tolerant of noise and small clock differences.

Encoding and decoding a frame

The simulation below builds the bit sequence of a frame, then decodes it the way a receiver does, including the two error conditions you will meet on real hardware: a parity error (a data bit flipped) and a framing error (the stop bit is not high, usually a baud mismatch or a break condition).

C UART frames: encode, corrupt, decode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Look at the frame for A (0x41): after the start bit 0 comes 10000010, which is 0x41 written backwards because the least significant bit goes first. Hardware UARTs also report an overrun error when a new byte arrives before software has read the previous one. That is a software problem: the fix is an interrupt or DMA with a ring buffer, not a bigger baud error budget.

Choosing the baud divisor

A UART derives its bit clock by dividing the peripheral clock. With 16x oversampling the divisor is clk / (16 * baud), and because it must be a whole number (or a number with a few fractional bits) the real baud rate differs from the one you asked for. Both ends must agree within about 2 to 3%, because the receiver re-synchronizes only at the start bit and the error accumulates over the ten bits of a frame.

C Baud rate error for different crystals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The odd-looking 11.0592 MHz crystal is not a mistake: it is exactly divisible into all the standard baud rates, so those old designs get zero error. With the common 16 MHz clock, 115,200 baud gives a large error at a divisor of 9, which is why many chips use a fractional baud generator or a different oversampling ratio. Always compute the error rather than trusting that "it should work".

Flow control and other signals

UART has no built-in guarantee that the receiver keeps up. Hardware flow control adds two wires, RTS (request to send) and CTS (clear to send): the receiver deasserts its RTS when its buffer is nearly full and the sender stops. Software flow control sends XOFF and XON characters in-band, which breaks binary data. Many simple systems skip flow control and rely on a buffer large enough for the longest burst.

Voltage levels matter too. A microcontroller UART is TTL/CMOS level (0 and 3.3 V or 5 V). The classic RS-232 standard uses roughly plus and minus 12 V and inverted logic, so you need a level shifter chip. RS-485 uses a differential pair for long cables and multi-drop buses (Modbus RTU runs over it), and needs a driver-enable pin for half-duplex operation.

Turning bytes into packets

A UART delivers a stream with no boundaries. If one byte is lost or noise injects a stray byte, you must be able to find the next message start again. The usual recipe is a framing byte, a length, the payload, and a checksum. The parser below is a small state machine that consumes one byte at a time, exactly how an RX interrupt would feed it. It resynchronizes on the start byte after any error.

C A byte-wise packet parser with a checksum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Real protocols add more: escaping so the start byte can appear inside the payload (as SLIP and HDLC do), a CRC-16 instead of an additive checksum, sequence numbers, and a timeout that resets the parser if a packet stalls. The state-machine shape stays the same.

Common mistakes

  • Mismatched settings. Different baud, parity or stop bits produce garbage characters or framing errors. Check both ends first when output looks random.
  • Crossed wires. TX connects to the other side's RX, and the grounds must be joined.
  • Level mismatch. Never connect RS-232 voltages straight to a microcontroller pin.
  • Busy-waiting on transmit. Writing a long string by polling blocks the CPU for ms; use interrupts or DMA.
  • Using printf from an interrupt. It is slow and may not be reentrant.
  • Ignoring overrun errors. If you see them, your receive path is too slow or unbuffered.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In 8N1 framing, how many bit times does one byte take on the wire?

    One start bit, eight data bits and one stop bit make 10 bit times.
  2. 2. Which bit of a data byte does a UART send first?

    UART transmits the data bits least significant bit first, after the start bit.
  3. 3. What typically causes a framing error?

    The receiver expects a high stop bit; if it samples low, bit timing is probably off or the line is in a break condition.
  4. 4. Why is a packet start byte plus length plus checksum useful on a UART stream?

    A raw UART stream has no message boundaries. Framing bytes and a checksum let the parser resynchronize after noise or loss.

Summary

  • A UART is a two-wire, clockless link; both sides must share baud rate and frame format (commonly 8N1).
  • A frame is start bit, data LSB first, optional parity, stop bit; errors show up as parity, framing and overrun flags.
  • Baud divisors rarely divide exactly: compute the error and keep it within about 2%.
  • Use interrupts or DMA with a ring buffer for receiving, and a small state machine to parse packets with length and checksum.

Next: The SPI Bus