LeepCast
Subscribe
All posts
Hardware

I2C vs SPI vs UART: How Embedded Serial Buses Work and How to Choose

What each of the three common embedded buses actually puts on the wire, what it costs in pins and bandwidth, and runnable Python examples that read a real sensor over I2C and SPI.

LeepCast8 min read
I2C vs SPI vs UART: How Embedded Serial Buses Work and How to Choose

Almost every sensor, display, flash chip or radio module talks to its host microcontroller or single-board computer over one of three serial interfaces: I2C, SPI or UART. Breakout boards often expose two of them, datasheets assume you already know the differences, and a poor choice shows up later as a bus that will not go faster, a pin budget that does not fit, or data that arrives garbled. This explainer walks through how each one works at the wire level, what it costs, and how to pick between them.

The short version

  • UART: two data wires (TX and RX), no shared clock, strictly point-to-point between two devices. A natural fit for debug consoles, GPS modules, modems and links between two processors.
  • I2C: two wires (SDA and SCL) shared by many devices, each selected by a 7-bit address. A natural fit for slow-to-moderate sensors and configuration registers where pin count matters more than speed.
  • SPI: a clock, two data lines and one chip-select line per device. A natural fit for displays, flash memory, fast ADCs and anything that needs megabits per second.

UART: two wires and an agreement about time

A UART (universal asynchronous receiver-transmitter) sends bytes without any clock wire. Instead, both ends agree in advance on a baud rate and a frame format, and the receiver times each bit from the moment it sees a frame begin. The line idles high. A frame starts with a start bit that pulls the line low, followed by the data bits (usually eight, sent least significant bit first), an optional parity bit, and one or two stop bits that return the line high.

The most common configuration is written 8N1: eight data bits, no parity, one stop bit. Every byte therefore costs ten bit-times on the wire, so the usable payload rate is the baud rate divided by ten. At 115200 baud that is at most 11,520 bytes per second.

Two practical rules trip people up. First, the wires cross: one device's TX goes to the other's RX and vice versa, because each label describes that device's own point of view. Second, a UART link is designed for exactly two devices. There is no addressing, and connecting two transmitters to one line causes contention. If the two baud rates do not match, the receiver samples bits at the wrong moments and produces garbage rather than an error message, which is why a stream of random characters on a serial console almost always means a baud rate mismatch.

On a Raspberry Pi, the header UART uses GPIO14 (TXD, pin 8) and GPIO15 (RXD, pin 10), and the /dev/serial0 symlink points to whichever UART is primary on that model. The official documentation notes that the simpler mini UART used on some models has no parity bit and no framing-error detection, and is more prone to losing characters at higher baud rates than the full PL011 UART.

I2C: a shared two-wire bus with addresses

I2C uses two lines: SDA for data and SCL for the clock. Both are open-drain, meaning a device can only pull a line low or let go of it, and pull-up resistors bring it back high. This wired-AND arrangement is what lets many devices share the same two wires safely, because no device ever drives a line high while another drives it low. The controller (older documents say master) generates the clock and begins every transaction.

A transaction begins with a START condition, defined as SDA falling while SCL is high, and ends with a STOP condition, SDA rising while SCL is high. After START, the controller sends a 7-bit target address followed by a read/write bit. Every byte is followed by a ninth clock pulse in which the receiver acknowledges by pulling SDA low. If SDA stays high, that is a NACK, which is how a controller learns that nothing answered at an address. To read a register, the controller usually writes the register number, then issues a repeated START without releasing the bus and switches to reading.

The NXP I2C specification (UM10204) defines several speed grades: up to 100 kbit/s in Standard-mode, 400 kbit/s in Fast-mode, 1 Mbit/s in Fast-mode Plus and 3.4 Mbit/s in High-speed mode, plus a unidirectional 5 Mbit/s Ultra Fast-mode. Most everyday sensors run at 100 or 400 kHz. The practical limit is often electrical: the specification caps bus capacitance at 400 pF for Standard and Fast modes (550 pF for Fast-mode Plus), and every device, connector and centimetre of wire adds capacitance that slows the rising edges the pull-ups must produce.

A few more details are worth knowing. A target may hold SCL low to pause a transfer while it catches up, which is called clock stretching, although the specification notes that most targets cannot do it. Two groups of eight addresses are reserved, so fewer than 128 addresses are really available. Address collisions are a real constraint too: two identical sensors with a fixed address cannot share a bus unless the part offers an address-select pin. On a Raspberry Pi, GPIO2 (SDA) and GPIO3 (SCL) already have 1.8 kΩ pull-ups to 3.3 V on the board, so external resistors are often unnecessary.

SPI: fast, full duplex and loosely defined

SPI uses a clock line (SCLK), two data lines and a chip-select line. The data lines are traditionally named MOSI and MISO; newer documents often use SDO and SDI, or COPI and CIPO. The controller pulls one device's chip select low to select it, and each clock pulse then shifts one bit out of the controller and one bit back from the device at the same time. A transfer is two shift registers swapping contents, so SPI is inherently full duplex, and even a read involves clocking bytes out.

Because nothing has to be open-drain and there is no addressing or acknowledgment overhead, SPI runs far faster than I2C. The protocol itself sets no maximum clock rate; each device's datasheet does, and tens of megahertz are common. The cost is pins: each extra device normally needs its own chip-select line, although some parts can be daisy-chained behind a single select.

SPI is a de facto standard that grew out of Motorola parts in the 1980s rather than a formal specification, so devices differ in the details. The most important one is the clock mode. CPOL sets whether the clock idles low (0) or high (1), and CPHA sets whether data is sampled on the first or second clock edge. Together they give modes 0 to 3, and the controller must be configured to match the device. SPI also has no built-in acknowledgment or error checking, so a disconnected device can return all ones or all zeros without any protocol-level complaint.

Worked example: what a six-byte sensor read costs

Consider reading six bytes of measurement data starting at one sensor register, a typical pattern for environmental and motion sensors.

  • I2C at 400 kHz: address plus write bit (9 clocks including ACK), register number (9), repeated START, address plus read bit (9), six data bytes with ACK or NACK (54), then STOP. That is 81 clock periods, roughly 203 µs, to move 48 bits of payload, before counting START and STOP timing.
  • SPI at 10 MHz: one register-address byte plus six data bytes is 56 clock periods, or 5.6 µs.
  • UART at 115200 baud, 8N1: the two sides would need their own command protocol on top, but even seven raw bytes take 70 bit-times, about 608 µs.

For a temperature reading once a second, any of these is effectively free. For a display refresh, an audio stream or reading a flash chip, a gap of one or two orders of magnitude decides the design.

Talking to a real part from Linux

The Bosch BME280 environmental sensor makes a good illustration because it supports both I2C and SPI. Its datasheet lists I2C up to 3.4 MHz and SPI up to 10 MHz in modes 0 and 3. Its 7-bit I2C address is 0x76 when the SDO pin is tied to ground or 0x77 when it is tied to VDDIO, and its id register at 0xD0 always reads 0x60, which makes a handy connectivity check. Over I2C with the smbus2 Python library:

python
from smbus2 import SMBus

BME280_ADDR = 0x76   # 0x77 if SDO is tied to VDDIO
REG_ID = 0xD0

with SMBus(1) as bus:   # opens /dev/i2c-1; run `ls /dev/i2c-*` to see your buses
    chip_id = bus.read_byte_data(BME280_ADDR, REG_ID)

print(f"chip id: 0x{chip_id:02X}")   # a BME280 reports 0x60

The same check over SPI uses the spidev library. In SPI mode the BME280 treats the most significant bit of the register byte as the read flag, and 0xD0 already has that bit set, so the read is a two-byte exchange: send 0xD0, then clock out one dummy byte while the answer comes back.

python
import spidev

spi = spidev.SpiDev()
spi.open(0, 0)                 # /dev/spidev0.0: bus 0, chip select 0
spi.mode = 0                   # BME280 supports modes 0 and 3
spi.max_speed_hz = 1_000_000   # well under the 10 MHz limit

try:
    # Byte 1: register address with the read bit (MSB) set.
    # Byte 2: a dummy byte clocked out while the reply comes back.
    reply = spi.xfer2([0xD0, 0x00])
finally:
    spi.close()

print(f"chip id: 0x{reply[1]:02X}")   # expect 0x60

One wiring caveat from the datasheet: the BME280 picks its interface at power-up, and if its CSB pin is pulled low it locks into SPI mode and stops responding to I2C until it is reset. Breakout boards usually handle this, but it is a classic cause of a sensor that seems to vanish. On Raspberry Pi OS, both buses must also be switched on first under Interface Options in raspi-config.

How to choose

  1. Linking two processors, attaching a GPS or modem, or adding a debug console: use a UART. It is the only one of the three that needs no shared clock, and USB-to-serial adapters make it easy to reach from a laptop.
  2. Several slow sensors and few free pins: use I2C. Check addresses for collisions before buying parts, keep wiring short and confirm the pull-ups.
  3. Displays, flash, fast ADCs, or a device that only offers SPI: use SPI, and budget one GPIO per chip select.
  4. A part that supports both I2C and SPI: start with I2C for convenience and switch to SPI when bandwidth or bus loading demands it.
  5. Whatever you choose, confirm the electrical side: matching logic voltages (3.3 V versus 5 V), a common ground, and for SPI the correct clock mode.

Debugging checklist

  • Garbled UART text: mismatched baud rate or frame format, or TX and RX not crossed.
  • I2C device missing from a scan: wrong address, missing pull-ups, interface not enabled, or a device that locked into another mode.
  • I2C works on the bench but fails in the enclosure: extra cable length and capacitance are slowing the edges, so lower the clock rate or shorten the wiring.
  • SPI reads all 0x00 or 0xFF: wrong chip select, wrong clock mode, MISO not connected, or an unpowered device.
  • Anything intermittent: a logic analyzer with protocol decoding shows what is actually on the wire, which is faster than guessing.

The three buses solve different problems. UART trades speed and sharing for simplicity, I2C trades speed for minimal wiring, and SPI trades pins for raw throughput. Knowing what each one puts on the wire makes datasheets easier to read and turns most interface bugs into a quick check instead of an afternoon of guesswork.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments