Communication Protocols and Interfaces Explained: SPI, I2C, UART, USART, CAN, Ethernet, USB, RS-232, RS-485 and More
Modern electronic systems are distributed systems. Even a small product can include a microcontroller, sensors, power-management ICs, memory, a wireless module, and a gateway to cloud services. None of those blocks are useful in isolation. They must communicate.
This guide is for engineers who want practical understanding, not only textbook definitions. You will find side-by-side protocol comparisons, real-world selection advice, interview questions, and production-focused best practices.
Introduction: What Communication Protocols Are and Why They Matter
A communication protocol is a rule set that defines how data is represented, transmitted, acknowledged, and validated between devices.
A communication interface is the physical and electrical mechanism that carries signals between devices.
In practice, real systems combine multiple layers:
- Physical/electrical layer: voltage levels, differential/single-ended signaling, connectors, cable type
- Link layer: framing, addressing, arbitration, error detection
- Network/transport/application layers: routing, sessions, publish/subscribe behavior, payload definitions
Why devices need communication interfaces
Devices communicate to:
- Read sensors and actuate outputs
- Move firmware, logs, and diagnostics
- Coordinate distributed control loops
- Integrate with supervisory systems (SCADA, vehicle ECUs, cloud dashboards)
- Enable manufacturing test and field service
A product with poor communication design usually fails in one of these areas:
- Reliability (intermittent faults, packet loss)
- Maintainability (hard to debug, no diagnostics)
- Scalability (cannot add nodes/features)
- Compliance (automotive/industrial requirements unmet)
Important note: A protocol choice is not only a software decision. It is always a system-level decision involving hardware layout, EMC environment, cable length, latency budget, node count, and certification constraints.
Protocol vs physical interface (common confusion)
- RS-485 defines electrical signaling for a differential serial bus.
- Modbus RTU defines message format and function codes often carried on RS-485.
- Ethernet defines physical and data-link aspects.
- TCP/IP, UDP, MQTT, Modbus TCP operate above Ethernet.
Engineers often say “we use Modbus” when they actually mean “Modbus RTU over RS-485” or “Modbus TCP over Ethernet.” Be explicit in design documents.
Quick Comparison Table: UART, USART, SPI, I2C, CAN, CAN FD, RS-232, RS-485, USB, Ethernet, LIN, Modbus, MQTT
| Protocol | Typical Speed | Distance | Number of Devices | Complexity | Cost | Common Applications |
|---|---|---|---|---|---|---|
| UART | 9.6 kbps to 3 Mbps | Short to medium (board to cable) | 2 point-to-point | Low | Low | Debug console, module communication |
| USART | Similar to UART, can be higher in sync mode | Short to medium | 2 (typical) | Low to medium | Low | Flexible serial links, legacy synchronous protocols |
| SPI | 1 Mbps to 100+ Mbps (device dependent) | Very short (PCB) | 1 master, multiple slaves | Low to medium | Low | Flash, displays, ADC/DAC, high-speed sensors |
| I2C | 100 kbps, 400 kbps, 1 Mbps, 3.4 Mbps | Short (PCB/cable with care) | Multi-drop with addressing | Low to medium | Very low | Sensors, PMICs, EEPROM, board control |
| CAN | Up to 1 Mbps (Classical CAN) | Up to hundreds of meters (lower speeds) | Multi-node bus | Medium | Medium | Automotive, industrial control, marine |
| CAN FD | Arbitration up to 1 Mbps, data phase typically 2-8 Mbps | Similar bus constraints | Multi-node bus | Medium to high | Medium | Modern automotive and industrial ECUs |
| RS-232 | Typically up to 115.2 kbps (higher possible) | ~15 m typical practical range | Point-to-point | Low | Low | Legacy serial ports, lab equipment |
| RS-485 | Commonly 9.6 kbps to 10 Mbps (distance dependent) | Up to 1200 m at low rates | Multi-drop (32+ nodes with transceivers) | Medium | Low to medium | Industrial networks, Modbus RTU, building automation |
| USB | 1.5 Mbps, 12 Mbps, 480 Mbps, 5 Gbps+ | Short cable lengths | Host-centric topology via hubs | Medium to high | Medium | PC peripherals, firmware update, CDC, HID |
| Ethernet | 10/100/1000 Mbps and beyond | 100 m per copper segment (typical) | Switched network, very large | Medium to high | Medium | Embedded Linux, gateways, cloud and LAN connectivity |
| LIN | Up to 20 kbps | Automotive local subnet distances | 1 master, multiple slaves | Low | Very low | Automotive body electronics |
| Modbus (RTU/TCP) | RTU: serial-rate bound, TCP: Ethernet-rate bound | RS-485 or Ethernet dependent | Multi-device | Low to medium | Low | PLCs, drives, meters, SCADA |
| MQTT | Application-layer protocol over TCP/IP | Network/cloud scale | Many clients via broker | Medium | Low software cost | IoT telemetry, remote monitoring, event distribution |
Important note: Distances and speeds are practical ranges, not absolute limits. PCB quality, transceivers, cabling, grounding, and EMC environment can shift real performance significantly.
UART Protocol Explained
How UART works
UART (Universal Asynchronous Receiver/Transmitter) sends serial data without a shared clock line.
Two devices agree on:
- Baud rate (bit rate)
- Data bits (often 8)
- Parity (none/even/odd)
- Stop bits (1 or 2)
This is commonly written as 115200 8N1.
Each frame typically includes:
- 1 start bit (low)
- 5 to 9 data bits
- optional parity
- 1 or more stop bits (high)
TX/RX communication
TXof device A goes toRXof device BRXof device A goes toTXof device B- Ground reference must be shared
flowchart LR
MCU_A_TX --> MCU_B_RX
MCU_B_TX --> MCU_A_RX
GND_A --- GND_B
Asynchronous communication characteristics
Because there is no separate clock wire, timing tolerance matters. Internal clocks must be accurate enough so sampling points stay valid across the frame.
Typical baud rates
- 9600
- 19200
- 38400
- 57600
- 115200
- 230400
- 921600
- 1M+ (platform dependent)
Advantages
- Very simple hardware and software
- Low pin count (TX, RX, GND)
- Excellent for logs, CLI, and bootloader interfaces
Limitations
- Usually point-to-point only
- No built-in addressing/arbitration
- No inherent error correction (beyond parity)
- Limited long-distance robustness unless converted to RS-232/RS-485 levels
Typical use cases
- Debug console from MCU to USB-UART adapter
- GNSS and cellular module interfaces
- Bootloader flashing and diagnostics
- Console access to Linux SBCs (Raspberry Pi, custom SoMs)
STM32 UART debug example (HAL, C)
#include "usart.h"
#include <string.h>
void debug_log(const char *msg)
{
HAL_UART_Transmit(&huart2, (uint8_t *)msg, strlen(msg), 100);
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_USART2_UART_Init();
debug_log("System booted\r\n");
while (1) {
debug_log("Heartbeat\r\n");
HAL_Delay(1000);
}
}
USART Explained: Difference from UART and When to Use It
USART (Universal Synchronous/Asynchronous Receiver/Transmitter) is a superset in many MCUs.
- UART mode: asynchronous (no external clock)
- Synchronous mode: transmitter provides/uses clock line
Synchronous vs asynchronous modes
- Asynchronous: simpler wiring, widely used for debug and module comms
- Synchronous: can provide tighter timing and potentially higher reliability in some designs
When USART is preferred
Use USART when you need one peripheral block to support multiple serial styles, or when a legacy synchronous serial requirement exists.
In many projects, engineers still use USART peripherals in UART mode, because that is what the external device expects.
Design tip: Check MCU reference manual carefully. Vendor naming differs. Some devices call all serial peripherals UART even if features overlap with USART behavior.
SPI Protocol Explained: High-Speed Peripheral Bus
SPI (Serial Peripheral Interface) is a synchronous master-slave bus optimized for short-distance, high-speed communication.
SPI signal lines
MOSI: Master Out, Slave InMISO: Master In, Slave OutSCK: Serial Clock from masterCS/SS: Chip Select (per slave, typically active low)
flowchart LR
M[Master MCU]
S1[Flash]
S2[Display]
S3[ADC]
M -- MOSI/MISO/SCK --> S1
M -- MOSI/MISO/SCK --> S2
M -- MOSI/MISO/SCK --> S3
M -- CS1 --> S1
M -- CS2 --> S2
M -- CS3 --> S3
Full-duplex communication
SPI shifts bits in both directions simultaneously. While master sends one byte, it also receives one byte.
Master/slave architecture
- One master controls clock and selects active slave
- Multiple slaves can share MOSI/MISO/SCK, each with own CS line
Advantages
- High throughput compared with UART/I2C
- Simple framing for many peripherals
- Deterministic timing (clocked by master)
- Good for low-latency peripheral transfers
Disadvantages
- More wires than I2C
- No built-in addressing
- No native multi-master arbitration in common usage
- Longer distances are problematic (signal integrity)
Common SPI peripherals
- NOR/NAND flash memory
- TFT/OLED displays
- Fast sensors (IMU, ADC)
- DAC/ADC converters
Linux userspace SPI example (spidev, C)
#include <fcntl.h>
#include <linux/spi/spidev.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/dev/spidev0.0", O_RDWR);
if (fd < 0) return 1;
uint8_t mode = SPI_MODE_0;
uint32_t speed = 10000000; // 10 MHz
ioctl(fd, SPI_IOC_WR_MODE, &mode);
ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
uint8_t tx[] = {0x9F, 0x00, 0x00, 0x00}; // JEDEC ID command
uint8_t rx[sizeof(tx)] = {0};
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = sizeof(tx),
.speed_hz = speed,
.bits_per_word = 8,
};
if (ioctl(fd, SPI_IOC_MESSAGE(1), &tr) < 1) {
close(fd);
return 2;
}
printf("Flash ID: %02X %02X %02X\n", rx[1], rx[2], rx[3]);
close(fd);
return 0;
}
I2C Protocol Explained: Two-Wire Addressed Bus
I2C (Inter-Integrated Circuit) is a synchronous, addressed, multi-drop bus using two lines.
I2C signal lines
SDA: Serial DataSCL: Serial Clock
Both are open-drain/open-collector style, requiring pull-up resistors.
Addressing and multi-device communication
- 7-bit addressing is most common
- 10-bit addressing exists for larger address space
- Master initiates communication with START condition and address+R/W bit
Multi-master capability
I2C supports multi-master arbitration in theory and in many controllers. In practice, many designs use single master for simplicity.
Pull-up resistors and why they matter
Since lines are open-drain, devices pull low but never drive high. Pull-ups define rise time and affect maximum speed and bus stability.
Typical values: 1 kOhm to 10 kOhm depending on voltage, bus capacitance, speed, and node count.
Advantages
- Very low pin count
- Easy to connect many low-speed peripherals
- Address-based communication reduces CS line explosion
Disadvantages
- Slower than SPI for high-throughput needs
- Bus capacitance limits speed and length
- Address collisions possible
- Debugging bus lockups can be tricky
Common use cases
- Temperature/pressure sensors
- RTC devices
- EEPROM
- PMIC configuration and board management
STM32 I2C sensor read example (HAL, C)
#include "i2c.h"
#include <stdint.h>
#define TMP102_ADDR (0x48 << 1) // HAL expects shifted 8-bit address
#define TMP102_REG_TEMP 0x00
float read_temp_c(void)
{
uint8_t reg = TMP102_REG_TEMP;
uint8_t raw[2] = {0};
HAL_I2C_Master_Transmit(&hi2c1, TMP102_ADDR, ®, 1, 100);
HAL_I2C_Master_Receive(&hi2c1, TMP102_ADDR, raw, 2, 100);
int16_t value = (int16_t)((raw[0] << 8) | raw[1]);
value >>= 4;
if (value & 0x0800) value |= 0xF000; // sign extend
return value * 0.0625f;
}
Debug note: If the I2C bus hangs low, check pull-up sizing, clock stretching support, and recovery sequence (toggle SCL manually and reinit peripheral).
SPI vs I2C: Practical Engineering Comparison
Speed
- SPI is usually faster and lower-latency
- I2C is sufficient for many sensors/configuration tasks
Wiring
- I2C: 2 shared wires (+power/ground)
- SPI: 3 shared + one CS per slave
Complexity
- I2C reduces pin count but adds addressing and bus-management nuances
- SPI is electrically simple but needs more routing for many devices
Device count
- I2C scales well with many low-speed devices
- SPI scales with additional CS lines or external decoders
Reliability
- SPI can be more robust at high speed on short, controlled PCB traces
- I2C can be very reliable if capacitance, pull-ups, and layout are correct
Which one to choose?
Choose SPI when:
- You need high throughput (display/framebuffer/flash)
- Deterministic, low-latency transfers matter
Choose I2C when:
- You need minimal pin count
- Bandwidth is moderate/low
- Many peripheral ICs share the bus
CAN Bus Explained: Arbitration, Reliability, and Real-World Networks
Short history
CAN (Controller Area Network) was developed by Bosch for robust in-vehicle communication without heavy point-to-point wiring.
It became dominant in:
- Automotive ECUs
- Industrial controllers
- Marine and off-highway systems
Message-based model
CAN is message-oriented, not address-oriented like UART point-to-point links.
- Frames carry an identifier (ID)
- ID defines message meaning and priority
- Any node can receive and process relevant frames
Arbitration and priority
CAN uses non-destructive bitwise arbitration:
- Lower numerical ID = higher priority
- Competing nodes transmit simultaneously
- Dominant bits override recessive bits
- Losing node stops and retries without corrupting bus
sequenceDiagram
participant ECU1 as Node A (ID 0x100)
participant BUS as CAN Bus
participant ECU2 as Node B (ID 0x080)
ECU1->>BUS: Start transmitting 0x100
ECU2->>BUS: Start transmitting 0x080
Note over BUS: Arbitration bit where A sends recessive and B sends dominant
BUS-->>ECU1: Lost arbitration, stop transmit
ECU2->>BUS: Continues frame successfully
ECU1->>BUS: Retries after bus idle
Error detection and fault confinement
Classical CAN includes:
- CRC checks
- Frame format checks
- ACK monitoring
- Bit monitoring and stuffing checks
- Error counters with active/passive/bus-off states
This makes CAN robust in noisy environments.
Reliability and applications
- High reliability under EMI
- Deterministic priority behavior
- Strong ecosystem of analyzers, stacks, and tools
Common domains:
- Automotive powertrain/body/chassis
- Marine networks
- Industrial automation
CANopen, J1939, NMEA 2000
These are higher-layer ecosystems over CAN:
- CANopen: industrial device profiles, PDO/SDO model
- J1939: heavy-duty vehicle communication with standardized PGNs
- NMEA 2000: marine network standard using CAN physical/link foundation
Engineering note: CAN provides transport and arbitration. Application interoperability comes from higher-layer standards (for example J1939 SPNs, NMEA2000 PGNs).
CAN FD Explained: What Changed from Classical CAN
CAN FD (Flexible Data-rate) extends Classical CAN.
Key differences
- Payload up to 64 bytes (vs 8 bytes in Classical CAN)
- Higher data phase bit rate after arbitration phase
- Improved efficiency for larger payloads
Advantages
- Better bus utilization
- Reduced frame overhead for larger datasets
- Useful for software updates, diagnostics, richer sensor data
Modern applications
- ADAS and domain controllers
- EV battery management communication
- Industrial machine networking with larger telemetry packets
Migration notes:
- Transceivers/controllers must support CAN FD
- Mixed Classical and FD networks require careful compatibility planning
RS-232 and RS-485 Explained for Industrial and Legacy Serial Systems
RS-232
- Single-ended signaling
- Point-to-point communication
- Legacy but still widely used in instrumentation
Common properties:
- Practical distance around 15 m (depending on baud, cable, environment)
- Vulnerable to ground offsets and noise in harsh environments
RS-485
- Differential signaling (A/B lines)
- Stronger noise immunity
- Multi-drop network capability
Common properties:
- Long cable support (up to ~1200 m at lower rates)
- Half-duplex 2-wire or full-duplex 4-wire options
- Requires termination and often bias resistors
Industrial usage and Modbus
RS-485 is a standard physical layer for:
- PLC to sensor/actuator networks
- Energy meters
- VFD and drive communication
- Building automation
Modbus RTU is frequently carried over RS-485.
Minimal Modbus RTU framing idea
- Address byte
- Function code
- Data payload
- CRC16
Field tip: Many RS-485 issues come from wiring, not software. Check polarity, termination at both ends only, common reference strategy, and stub lengths.
Ethernet in Embedded Systems: TCP/IP, UDP, Switching, and Real-Time Concerns
TCP/IP fundamentals in embedded context
- IP handles addressing and routing
- TCP provides reliable ordered byte stream with retransmission
- UDP provides low-overhead datagrams without guaranteed delivery
TCP vs UDP
Use TCP when:
- Data integrity and ordering are mandatory
- You need easy interoperability with web/cloud stacks
Use UDP when:
- Latency and minimal overhead are critical
- Application can tolerate loss or handle reliability itself
Switching and modern network topology
Ethernet in modern systems is switched, not shared-collision bus (as in old hubs).
Benefits:
- Full-duplex links
- Better throughput and segmentation
- VLAN/QoS options in managed networks
Real-time considerations
Standard Ethernet is not deterministic by default. For hard real-time behavior, teams use:
- Time-sensitive networking (TSN) features
- Industrial Ethernet protocols (PROFINET, EtherCAT, Ethernet/IP, etc.)
- Careful network architecture and QoS planning
Embedded Linux use cases
Ethernet is central for:
- SSH and remote shell
- OTA update systems
- REST/MQTT gateways
- Log upload and remote diagnostics
Linux socket UDP example (C)
#include <arpa/inet.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in dst = {0};
dst.sin_family = AF_INET;
dst.sin_port = htons(5000);
inet_pton(AF_INET, "192.168.1.100", &dst.sin_addr);
const char *msg = "status=ok";
sendto(sock, msg, strlen(msg), 0, (struct sockaddr *)&dst, sizeof(dst));
close(sock);
return 0;
}
Industrial and marine applications
- Plant-level data aggregation gateways
- Marine bridge systems integrating NMEA/can-based subsystems with IP networks
- Remote service tunnels and fleet diagnostics
USB Explained: Host/Device Model, Classes, and Power
USB is ubiquitous but more complex than UART/SPI/I2C.
Host/device model
- One host controls bus transactions
- One or more devices respond
- Hubs expand topology
Most MCUs implement USB device mode. Some support OTG/host.
USB classes in embedded products
Common classes:
- CDC ACM (virtual serial port)
- HID (human interface device)
- MSC (mass storage)
- Audio, Video, DFU (device firmware update)
Power delivery basics
- USB can supply power (current limits depend on version/negotiation)
- USB-C with PD enables higher power profiles
- Embedded design must handle inrush, protection, and role negotiation correctly
Typical embedded applications
- USB-to-serial debug and CLI
- Firmware update via DFU or MSC drag-and-drop
- Data logger export as mass storage
- Human interface accessories
Common mistake: Treating USB like “just serial.” Enumeration, descriptors, endpoint management, and host behavior add significant integration complexity.
LIN Bus Explained: Why It Exists and How It Compares with CAN
LIN (Local Interconnect Network) is a low-cost automotive serial network designed for non-critical body electronics.
Why LIN exists
Automotive systems needed a cheaper complement to CAN for simple nodes:
- Window lifters
- Mirror control
- Seat modules
- Climate flap actuators
Characteristics
- Single master, multiple slaves
- Scheduled deterministic polling model
- Up to ~20 kbps
- Lower wiring and transceiver cost than CAN
LIN vs CAN
- LIN is cheaper and simpler, but much slower
- CAN is more robust and supports multi-master arbitration and higher reliability
- In vehicles, LIN often connects simple local modules, while CAN/CAN FD carries critical and higher-throughput traffic
MQTT Explained: Publish/Subscribe for IoT and Cloud Integration
MQTT (Message Queuing Telemetry Transport) is not a physical bus. It is an application-layer protocol over TCP/IP, commonly used in IoT.
Publish/Subscribe architecture
- Clients publish messages to topics
- Broker routes messages to subscribers
- Producers and consumers are decoupled
flowchart LR
S1[Sensor Node] -->|publish temp/site1| B[MQTT Broker]
S2[Gateway] -->|publish status/site1| B
B -->|subscribe temp/site1| D1[Dashboard]
B -->|subscribe status/#| D2[Cloud Service]
Why MQTT is different from hardware buses
- Runs over IP networks, not board-level wires
- Scales across LAN, WAN, and cloud
- Topic-based routing instead of electrical bus arbitration
IoT applications
- Remote telemetry from gateways
- Device status/event streaming
- Command and control channels
- Cloud data ingestion pipelines
QoS levels
- QoS 0: at most once
- QoS 1: at least once
- QoS 2: exactly once (highest overhead)
Real-World Examples: STM32, Linux, CAN, and MQTT in Practical Systems
1) STM32 communicating with sensors over I2C
Typical architecture:
- STM32 polls environmental sensor every 100 ms
- Applies calibration/filtering
- Exposes values via UART debug and CAN telemetry
Key design decisions:
- Non-blocking I2C with DMA/interrupts for responsiveness
- Timeout and bus-recovery logic
- Unit tests for scaling/compensation math
2) LCD display connected via SPI
Typical architecture:
- SPI at 20-40 MHz
- Dedicated DMA for frame transfer
- Double buffering to avoid tearing
Key decisions:
- Separate data/command GPIO with strict timing
- Keep traces short and impedance-aware on high-speed paths
- Verify display controller SPI mode (CPOL/CPHA)
3) Debug console using UART
Typical architecture:
- Boot ROM/bootloader prints early logs
- Main firmware provides command shell (
help,status,reboot,dump) - Ring buffer + DMA for robust RX/TX
Benefit:
- Fast bring-up and field diagnostics with minimal overhead
4) Vehicle network using CAN
Typical architecture:
- Multiple ECUs publish periodic status frames
- Safety-relevant IDs assigned high priority (lower ID)
- Gateway translates CAN frames to diagnostics over Ethernet
Validation:
- Bus load analysis at worst-case periodic rates
- Error frame monitoring under EMI tests
- DBC-driven signal decoding checks
5) Embedded Linux system connected through Ethernet
Typical architecture:
- ARM SoM runs Linux with static core services
- Remote diagnostics over SSH/VPN
- OTA updates and telemetry upload
Best practices:
- Separate control and diagnostics VLAN where possible
- Watchdog integration for network stack stalls
- Capture pcap traces for difficult intermittent faults
6) IoT gateway using MQTT
Typical architecture:
- Southbound: Modbus RTU over RS-485 from field devices
- Gateway normalizes data model
- Northbound: MQTT to cloud broker with TLS and retained status topics
Operational advice:
- Use persistent sessions when connectivity is unstable
- Define topic namespace early (
site/device/channel/metric) - Track message age and quality flags, not only raw values
Choosing the Right Protocol: Practical Decision Guide
If you need maximum speed
- On-board peripheral: SPI
- Networked systems: Ethernet
- Vehicle domain with larger payloads: CAN FD
If you need low pin count
- I2C (many low-speed peripherals on 2 wires)
- UART (simple point-to-point, 2 data pins)
If you need long distance
- RS-485 for robust serial field buses
- Ethernet for structured network infrastructure
- CAN for medium-distance robust networks in vehicles/machines
If you need high reliability in noisy environments
- CAN/CAN FD
- RS-485 with correct termination/shielding/ground strategy
If you need many devices on one network
- CAN/CAN FD for robust multi-node control
- I2C for short-distance board-level multi-device setups
- Ethernet for larger distributed systems
If you need Internet/cloud connectivity
- Ethernet or Wi-Fi + TCP/IP
- MQTT/HTTP at application layer
If you need automotive compatibility
- Body comfort low-cost: LIN
- Main ECU communication: CAN/CAN FD
- Heavy-duty and marine interoperability: J1939 / NMEA2000 over CAN
Selection rule: Start from requirements matrix: latency, throughput, cable length, node count, safety class, EMC environment, software ecosystem, and cost target.
Embedded Protocol Interview Questions and Answers (18 Practical Q&A)
1. What is the main difference between UART and USART?
UART is asynchronous only; USART typically supports both asynchronous and synchronous serial modes.
2. Why does I2C need pull-up resistors?
SDA/SCL are open-drain lines. Devices can pull low but cannot drive high; pull-ups restore logic high.
3. Why is SPI usually faster than I2C?
SPI uses push-pull clock/data and simpler framing, allowing higher clock rates and lower protocol overhead.
4. What happens if two CAN nodes transmit simultaneously?
Bitwise arbitration resolves it non-destructively. Higher-priority (lower ID) message continues.
5. Why is CAN considered robust in automotive environments?
Differential signaling, strong error detection, fault confinement, and deterministic arbitration.
6. What is the practical difference between CAN and CAN FD?
CAN FD allows larger payloads (up to 64 bytes) and faster data phase, improving bandwidth efficiency.
7. RS-232 vs RS-485: when should you use each?
Use RS-232 for short point-to-point links; RS-485 for long-distance multi-drop noisy industrial environments.
8. Why does RS-485 need termination resistors?
To match line impedance and reduce reflections, especially at higher speeds/longer cables.
9. What are common UART framing settings?
Typical setting is 8 data bits, no parity, 1 stop bit (8N1) at selected baud rate.
10. Why can I2C addresses conflict?
Many devices have fixed or limited selectable addresses. Two same-address parts on one bus conflict.
11. What is clock stretching in I2C?
A slave holds SCL low to delay master when it needs more processing time.
12. Why is USB integration harder than UART?
USB requires enumeration, descriptors, endpoint configuration, and strict host-device protocol behavior.
13. When should you use UDP instead of TCP in embedded systems?
When low latency matters and occasional loss is acceptable or handled by application logic.
14. What is MQTT QoS and why does it matter?
QoS controls delivery guarantees (0/1/2), balancing reliability and overhead for IoT messaging.
15. Is MQTT a replacement for SPI/I2C/UART?
No. MQTT is application-layer messaging over IP. SPI/I2C/UART are hardware-level interfaces.
16. Why is shared ground important in UART links?
Without a common reference, logic levels are undefined and communication becomes unreliable.
17. What is bus load in CAN, and why monitor it?
Bus load is channel utilization. Excessive load increases latency and risk of deadline misses.
18. How do you choose between SPI and I2C for a new sensor board?
Choose SPI for high throughput/low latency; choose I2C for low pin count and many low-speed peripherals.
Best Practices: Protocol Selection, Debugging, and Signal Integrity
1) Protocol selection guidelines
Create a simple scoring sheet for each candidate protocol:
- Throughput required (payload + overhead)
- Deterministic latency requirement
- Cable length and topology
- Node count and addressing needs
- EMC/noise exposure
- Tooling availability (analyzers, stack maturity)
- Cost (BOM + engineering time + maintenance)
Avoid picking a protocol only because “team already uses it.” Re-evaluate per product generation.
2) Common engineering mistakes
- Ignoring physical layer limits while focusing only on software
- Underestimating bus loading and worst-case traffic
- No diagnostic counters in production firmware
- Bad grounding/shielding strategy
- Missing timeout/retry states in state machines
- Using blocking drivers in timing-critical contexts
3) Debugging tips by interface
UART/USART
- Verify baud and frame format first
- Check level compatibility (TTL vs RS-232 transceiver levels)
- Use logic analyzer decode to spot framing/parity issues
SPI
- Confirm CPOL/CPHA mode against peripheral datasheet
- Validate CS timing and setup/hold requirements
- Scope SCK edges and ringing at target speed
I2C
- Scan bus for addresses
- Measure rise times on SDA/SCL
- Implement bus recovery for stuck-low conditions
CAN/CAN FD
- Check bitrate/sample point configuration across all nodes
- Monitor error counters and bus-off events
- Use proper 120 Ohm termination at both bus ends only
RS-485
- Verify A/B polarity and common reference strategy
- Ensure proper end termination and bias network
- Reduce stub lengths to improve integrity
Ethernet
- Capture traffic with tcpdump/Wireshark
- Track packet loss/retransmits and link flaps
- Separate control and high-volume telemetry traffic when possible
4) Signal integrity and EMC considerations
- Keep high-speed traces short and controlled
- Avoid long stubs on differential buses
- Route differential pairs together and symmetrically
- Use proper decoupling near transceivers
- Plan cable shielding and chassis/earth strategy early
Production note: Many intermittent communication bugs appear only in EMC chamber, high temperature, or motor-load scenarios. Validate under realistic stress, not only bench conditions.
5) Firmware architecture recommendations
- Use interrupt/DMA-driven communication for performance
- Isolate protocol parsing from business logic
- Add counters: CRC errors, timeouts, retries, framing errors
- Log link-health metrics for field diagnostics
- Build protocol simulation tests for regression
Practical Linux and C/C++ Snippets for Daily Work
Linux serial console setup
# Configure serial port quickly
stty -F /dev/ttyUSB0 115200 cs8 -cstopb -parenb -ixon -ixoff
# View data
cat /dev/ttyUSB0
# Send test
echo "ping" > /dev/ttyUSB0
Quick CAN bring-up in Linux (SocketCAN)
# Configure CAN interface at 500 kbps
ip link set can0 down
ip link set can0 type can bitrate 500000
ip link set can0 up
# Monitor frames
candump can0
# Send frame
cansend can0 123#DEADBEEF
Minimal C++ wrapper idea for robust serial write
#include <cstdint>
#include <stdexcept>
#include <unistd.h>
ssize_t write_all(int fd, const uint8_t* data, size_t len)
{
size_t total = 0;
while (total < len) {
ssize_t n = write(fd, data + total, len - total);
if (n < 0) throw std::runtime_error("serial write failed");
total += static_cast<size_t>(n);
}
return static_cast<ssize_t>(total);
}
SEO FAQ: Protocol Selection Questions Engineers Often Search
What is the best communication protocol for STM32 sensors?
For many sensors, I2C is easiest. For high-speed sensors or displays, SPI is usually better.
Which is better for industrial systems: RS-485 or Ethernet?
RS-485 is robust and simple for field buses. Ethernet is better for high bandwidth and IT/cloud integration.
Is CAN better than UART for automotive systems?
Yes for multi-node robust in-vehicle communication. UART remains useful for diagnostics and local module links.
Is MQTT a hardware protocol like CAN or SPI?
No. MQTT is an application protocol over TCP/IP, typically for IoT/cloud messaging.
One-Page Cheat Sheet: Communication Protocols at a Glance
| Protocol | Layer/Type | Speed (Typical) | Distance (Typical) | Topology | Best For | Watch Out For |
|---|---|---|---|---|---|---|
| UART | Hardware serial, async | kbps to low Mbps | Short to medium | Point-to-point | Debug, module links | Clock mismatch, no addressing |
| USART | Hardware serial, sync/async | kbps to low Mbps+ | Short to medium | Point-to-point | Flexible serial interfaces | Mode/config complexity |
| SPI | Hardware serial, sync | Mbps to 100+ Mbps | Short PCB | Master-multi-slave | Flash, displays, high-speed peripheral IO | More wires, CS management |
| I2C | Hardware serial, sync addressed | 100 kbps to 3.4 Mbps | Short PCB | Multi-drop | Many low-speed ICs | Pull-up sizing, bus capacitance |
| CAN | Differential field bus | Up to 1 Mbps | Medium to long | Multi-master bus | Automotive/industrial reliable control | Payload 8 bytes, load planning |
| CAN FD | Differential field bus (enhanced) | Up to multi-Mbps data phase | Medium to long | Multi-master bus | Modern ECU networks, larger payloads | Controller/transceiver compatibility |
| RS-232 | Electrical serial standard | Low to moderate | Short cable | Point-to-point | Legacy equipment links | Noise, ground offsets |
| RS-485 | Differential serial standard | kbps to Mbps | Long cable | Multi-drop | Industrial serial networks | Termination/bias errors |
| USB | Host-device serial bus | 1.5 Mbps to multi-Gbps | Short cable | Host with hubs | PC connectivity, update, peripherals | Enumeration and stack complexity |
| Ethernet | Network physical/link | 10/100/1000+ Mbps | 100 m per copper segment | Switched network | Embedded Linux networking/cloud | Determinism without TSN |
| LIN | Automotive low-cost bus | Up to 20 kbps | Vehicle subnet | 1 master, many slaves | Body electronics | Low speed, limited scope |
| Modbus RTU/TCP | Application protocol | Serial/Ethernet dependent | Medium to long | Master-slave/client-server | Industrial PLC/meters | Data model mapping and timeouts |
| MQTT | Application protocol over TCP/IP | Network dependent | LAN/WAN/cloud | Pub/Sub via broker | IoT telemetry and commands | Topic design, QoS trade-offs |
Conclusion: When to Choose Each Protocol
There is no universal best protocol. There is only the best fit for your constraints.
- Choose UART/USART for simple serial links, debug channels, and low-cost module interfaces.
- Choose SPI when you need high speed on-board peripheral communication.
- Choose I2C when you need low pin count and many low-speed devices on one board.
- Choose CAN/CAN FD for robust multi-node communication in automotive, marine, and industrial environments.
- Choose RS-232/RS-485 when serial cabling distance and industrial noise conditions dominate your design.
- Choose USB for host-centric peripheral ecosystems and user-facing connectivity.
- Choose Ethernet when you need scalable networking, Linux integration, remote diagnostics, and cloud connectivity.
- Choose LIN for low-cost automotive body electronics.
- Choose MQTT when your system must publish/subscribe data over IP networks and cloud platforms.
The strongest engineering teams make protocol choices early, validate under real noise/load conditions, and design diagnostics from day one. That discipline saves months of late-stage debugging and creates products that are reliable in the field, not only on the lab bench.