SPI and UART are two ways devices talk to each other. Knowing their trade-offs helps pick the best one for your project.
0
0
SPI vs UART trade-offs in Embedded C
Introduction
You want fast data transfer between microcontrollers and sensors.
You need to send data over a simple two-wire connection.
You want to connect multiple devices on the same bus.
You have limited pins and want a simple setup.
You want to send data over longer distances with error checking.
Syntax
Embedded C
/* SPI and UART are hardware protocols, not code syntax, but here are basic setups in C */ // SPI setup example SPI_InitTypeDef SPI_Config = { .Mode = SPI_MODE_MASTER, .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_8BIT, .CLKPolarity = SPI_POLARITY_LOW, .CLKPhase = SPI_PHASE_1EDGE, .NSS = SPI_NSS_SOFT, .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16, .FirstBit = SPI_FIRSTBIT_MSB }; // UART setup example UART_InitTypeDef UART_Config = { .BaudRate = 9600, .WordLength = UART_WORDLENGTH_8B, .StopBits = UART_STOPBITS_1, .Parity = UART_PARITY_NONE, .Mode = UART_MODE_TX_RX };
SPI uses separate lines for clock and data, so it needs more wires.
UART uses two wires (TX and RX) and sends data one bit at a time without a clock.
Examples
This function sends a byte over SPI and waits to receive a byte back.
Embedded C
// SPI send and receive example uint8_t spi_send_receive(uint8_t data) { // Wait until TX buffer is empty while (!(SPI->SR & SPI_SR_TXE)); SPI->DR = data; // Send data // Wait until RX buffer is not empty while (!(SPI->SR & SPI_SR_RXNE)); return SPI->DR; // Return received data }
This function sends one character over UART.
Embedded C
// UART send example
void uart_send_char(char c) {
while (!(UART->SR & UART_SR_TXE)); // Wait until TX buffer empty
UART->DR = c; // Send character
}Sample Program
This simple program shows how you might send a message using SPI or UART depending on a choice.
Embedded C
#include <stdio.h> // Simulated SPI and UART send functions void spi_send(const char* msg) { printf("SPI sending: %s\n", msg); } void uart_send(const char* msg) { printf("UART sending: %s\n", msg); } int main() { // Choose communication method int use_spi = 1; // 1 for SPI, 0 for UART if (use_spi) { spi_send("Hello SPI"); } else { uart_send("Hello UART"); } return 0; }
OutputSuccess
Important Notes
SPI is faster and good for short distances but needs more wires.
UART is simpler with fewer wires but slower and usually for point-to-point links.
SPI can connect multiple devices easily; UART usually connects two devices only.
Summary
SPI is fast, uses more wires, and supports multiple devices.
UART is simple, uses fewer wires, and is good for longer distances.
Pick SPI for speed and multiple devices; pick UART for simplicity and fewer wires.