42 Sensor Communication Protocols
Key Concepts
- Modbus: Simple serial (RTU) and TCP/IP register-based protocol used in industrial automation since 1979; polling-only (no push), no built-in security, widely deployed in HVAC and energy metering
- I2C (Inter-Integrated Circuit): Short-distance (1m), low-speed (100kbps-3.4Mbps) two-wire bus (SDA/SCL) connecting microcontrollers to sensors and peripherals on the same PCB
- SPI (Serial Peripheral Interface): High-speed (1-100MHz) four-wire full-duplex bus for high-performance sensors (ADCs, IMUs, displays) requiring faster data rates than I2C
- 1-Wire Protocol: Single-wire bus enabling dozens of temperature sensors (DS18B20) on one GPIO pin, each identified by unique 64-bit ROM code
- RS-485: Multi-drop differential serial bus (1200m, 32+ devices) used with Modbus RTU for industrial wiring runs too long for RS-232 or I2C
- OPC-UA (OPC Unified Architecture): Platform-independent, SOA-based standard for industrial machine-to-machine communication with built-in security, information modeling, and service discovery
- NMEA 0183: Standard protocol for GPS receiver communication, providing location, speed, and heading data in comma-separated ASCII sentences
- Analog Sensor Interface: 4-20mA current loop or 0-10V voltage signal — legacy industrial standards immune to voltage drop over long cable runs, requiring ADC conversion at the gateway
Sensor Squad: The Three Communication Roads
Max the Microcontroller needed to talk to all his sensor friends, but each one lived on a different road!
I2C Road was a shared bus – like a single-lane road with house numbers. Sammy the Sensor, the humidity sensor, and the pressure sensor all shared this road. When Max wanted to talk to Sammy, he called out Sammy’s address number (0x76) and Sammy answered. Up to 127 friends could share this road, but they had to take turns talking!
SPI Highway was a super-fast four-lane highway. Lila the LED Display lived here because she needed lots of data delivered quickly. Each friend on SPI Highway had their own private driveway (chip select wire), so Max could zoom data to them at top speed. But each new friend needed another driveway, which used up Max’s connection pins.
UART Lane was a simple two-way street connecting just two houses. The GPS module lived here because it just needed a direct line to Max – no fancy addresses or speed needed, just a reliable conversation.
Bella the Battery whispered: “I2C Road is my favorite because it only uses 2 wires, so we save energy on wiring. But when Lila needs a fast screen update, SPI Highway is worth the extra wires!”
For Beginners: Sensor Communication Protocols
Think of sensor communication like different ways to deliver mail:
- I2C is like a shared mailbox system – many apartments (sensors) share one mailbox bank. Each has an apartment number (address). Cheap to set up but everyone waits their turn.
- SPI is like private courier delivery – very fast, but each recipient needs their own courier (chip select line). Best for important, time-sensitive deliveries.
- UART is like two tin cans connected by a string – simple, direct, connects just two people.
| Term | Simple Explanation |
|---|---|
| I2C | Two-wire bus where many sensors share the same wires, using addresses |
| SPI | Four-wire high-speed connection with a dedicated select wire per device |
| UART | Simplest serial link between two devices, no clock needed |
| Baud Rate | Speed of data transmission, like words-per-minute in typing |
| Pull-up Resistor | Component that keeps I2C wires at the right voltage when idle |
42.1 Learning Objectives
By the end of this chapter, you will be able to:
- Differentiate synchronous and asynchronous serial communication by clock, timing, and data framing characteristics
- Configure I2C two-wire multi-device bus communication for sensor networks with addressing and pull-up resistors
- Implement SPI high-speed synchronous interfaces for fast peripherals with chip select management
- Diagnose UART point-to-point serial communication issues including baud rate mismatches and framing errors
- Evaluate protocol trade-offs (I2C vs SPI vs UART) based on speed, pin count, and device requirements
42.2 Introduction
Deep dive into sensor-to-microcontroller protocols including I2C, SPI, UART, and system communication methods.
42.3 Sensor Communication Protocols
Now that we’ve learned about microcontrollers’ structure and selection criteria, we will consider the appropriate communication protocols for micros to communicate with sensors and other peripherals.
Alternative View: Protocol Selection Decision Tree
This decision tree helps select the right sensor-to-MCU protocol. Use I2C when you have many sensors sharing a bus with limited GPIO pins. Choose SPI for high-speed peripherals like displays or SD cards. UART works best for single devices needing simple serial debugging.
Serial communication protocol is the common protocol used for microcontroller communications. It involves transmitting a series of digital pulses between sender and receiver at a specified data rate, generally divided into synchronous and asynchronous categories.
42.3.1 Asynchronous Serial Communication
⭐⭐ Intermediate
In asynchronous serial communication, transmitter and receiver manually agree on the data rate, and each manages timing independently with no common clock. The data rate for the transmitter sending pulses must be the same as the receiver listening for pulses.
42.3.1.1 Required Agreement Parameters
The transmitter and receiver must agree on: - Data rate (baud rate) - Voltage level corresponding to 1 bit or 0 bit - Signal interpretation: High voltage = 1 and low voltage = 0, or inverted
42.3.1.2 Example: 9600 bps Communication
- Both transmitter and receiver agree on voltage level interpretation for 1 bit and 0 bit
- Both ends require a common ground connection to measure voltage with same reference point
- Wire connection for transmission from sender to receiver
- Wire connection for transmission from receiver to sender
When communication is established with agreed data rate (9600 bps), the receiver reads voltage constantly on the receiving wire and interprets it every 1/9600th of a second.
42.3.1.3 Voltage Levels
Generally, in most microcontrollers: - High voltage (+5V or +3.3V) represents 1 bit - Low voltage (0V) represents 0 bit
At the end of data transmission, the receiver rebuilds the original message using the interpreted bits from voltage levels.
42.3.1.4 Common Asynchronous Protocols
RS-232:
- Long-established standard
- ±12V signal levels
- Long cable runs (up to 15 meters)
- Common in industrial equipment
USB (Universal Serial Bus):
- High-speed asynchronous serial
- Host-device architecture
- Power delivery capability
- Hot-pluggable
42.3.2 Synchronous Serial Communication
⭐⭐ Intermediate
In synchronous serial communication, a clocking system manages synchronization between transmitter and receiver. The clock is either: - Embedded as part of the data frame, or - A separate clock wire manages timing during transmission
42.3.2.1 Clock Sharing
All devices in the communication line share the same clock data. With every clock pulse, one bit moves in the line. The clocking system directs devices regarding: - When to listen to incoming bits - When to discard them
This type of communication is used for simpler devices with no internal clock crystal and few memory registers.
42.3.2.2 Common Synchronous Protocols
I2C (Inter-Integrated Circuit):
- 2-wire bus (SDA: data, SCL: clock)
- Multi-master capable
- Address-based device selection
- Lower speed (100 kHz - 3.4 MHz)
- Good for many low-speed peripherals
SPI (Serial Peripheral Interface):
- 4-wire bus (MOSI, MISO, SCLK, SS/CS)
- Master-slave architecture
- Full-duplex communication
- Higher speed (up to tens of MHz)
- Good for high-speed, few peripherals
42.3.2.3 I2C vs SPI Comparison
| Feature | I2C | SPI |
|---|---|---|
| Wires | 2 (SDA, SCL) | 4 (MOSI, MISO, SCLK, SS) |
| Topology | Multi-master bus | Master-slave |
| Speed | 100 kHz - 3.4 MHz | Up to 50+ MHz |
| Device addressing | 7 or 10-bit addresses | Chip select pins |
| Max devices | ~127 devices | Limited by CS pins |
| Complexity | More complex protocol | Simpler protocol |
| Power | Lower | Slightly higher |
| Best for | Many slow peripherals | Few fast peripherals |
| Flow control | Built-in ACK/NACK | No built-in flow control |
42.3.2.4 Selection Guidelines
Putting Numbers to It
Why does I2C pin efficiency matter for multi-sensor boards? Let’s quantify the GPIO advantage:
For an ESP32 board connecting 8 environmental sensors:
I2C approach: \[\text{Pins required} = 2 \text{ (SDA + SCL, shared by all)}\]
SPI approach: \[\text{Pins required} = 3 \text{ (MOSI + MISO + SCK)} + 8 \text{ (CS per sensor)} = 11 \text{ pins}\]
If your MCU has only 12 available GPIO pins, I2C leaves you 10 pins free for other functions (LEDs, buttons, actuators), while SPI leaves only 1 pin – barely enough for status indication. The 450% pin efficiency (\(\frac{10}{2} = 5\) vs \(\frac{1}{11} = 0.09\)) often determines protocol selection for pin-constrained designs.
According to the distinctions between I2C and SPI:
- I2C is more suitable when:
- Large number of peripherals needed
- High data rate NOT required
- Pin count must be minimized
- Multi-master capability needed
- SPI is a good option when:
- Low power required
- High speed needed
- Few peripherals (pin count not constrained)
- Full-duplex communication needed
Both serial communication protocols are considered stable and robust for embedded applications. The critical part is ensuring both devices on a serial bus are configured to use the exact same protocols.
Tradeoff: I2C vs SPI for Sensor Communication
Option A: I2C (Inter-Integrated Circuit) - 2-wire bus (SDA + SCL) supporting up to 127 addressed devices at 100kHz-3.4MHz, ideal for connecting many low-speed sensors with minimal GPIO usage.
Option B: SPI (Serial Peripheral Interface) - 4-wire interface (MOSI, MISO, SCLK, CS) offering speeds up to 50+ MHz with dedicated chip select per device, ideal for high-speed peripherals like displays, ADCs, and SD cards.
Decision Factors:
Choose I2C when: GPIO pins are limited, connecting 5+ sensors (temperature, humidity, IMU), speed under 1 Mbps is acceptable, multi-master capability is needed, or built-in addressing eliminates need for chip select management.
Choose SPI when: High data rates are required (>1 Mbps), connecting displays or high-speed ADCs, full-duplex communication is needed, fewer than 4 peripherals (CS pins available), or simpler protocol reduces debugging complexity.
Common pattern: Use I2C for sensor clusters (environmental monitoring) and SPI for high-bandwidth peripherals (SD card logging, TFT display). Many designs use both buses for different device classes.
42.4 System Communication
The large amount of data collected by sensors must be transferred to servers on the Cloud for analysis and decision making. Then necessary actions are delivered back from the Cloud to microcontrollers.
Communication between sensors to computer/Cloud is done using communication protocols based on: - Power consumption requirements - Coverage requirements - Data rate requirements - Cost requirements
42.4.1 Ethernet (Wired)
A wired network is the traditional way of connecting devices to the Internet, practical for environments with wired connections, such as smart home systems.
Advantages:
- High reliability
- High data rates (100 Mbps - 10 Gbps)
- No interference
- Secure physical connection
Disadvantages:
- Requires cable infrastructure
- Not suitable for mobile devices
- Installation costs
Best for: Smart buildings, industrial IoT, data centers
Tradeoff: Wired (Ethernet) vs Wireless Connectivity for IoT
Option A: Wired Ethernet - Physical cable connection providing reliable, high-bandwidth, interference-free communication with Power over Ethernet (PoE) capability for device power.
Option B: Wireless (Wi-Fi, BLE, LoRa, Cellular) - Radio-based connectivity enabling flexible deployment, mobility, and reduced installation costs without cable infrastructure.
Decision Factors:
Choose Wired when: Devices are stationary in fixed locations, reliability is critical (industrial control, safety systems), high bandwidth is needed (video cameras, data loggers), PoE simplifies power distribution, or security requires physical network isolation.
Choose Wireless when: Devices are mobile or frequently relocated, cable installation is impractical or expensive, rapid deployment is needed, devices are battery-powered (wired adds power consumption), or legacy buildings lack cabling infrastructure.
Consider Both when: Backbone infrastructure uses Ethernet while wireless extends to end devices. Gateways bridge Ethernet backhaul with Wi-Fi/BLE sensor networks. This hybrid pattern combines reliability with flexibility.
42.4.2 Wireless Communication
However, in most IoT scenarios, Ethernet technology is not sufficient and some kind of wireless communication must be implemented based on power consumption, data rate, coverage, and cost.
Worked Example: I2C vs SPI Selection for Multi-Sensor Board
Scenario: An environmental monitoring PCB needs to connect 8 sensors to an ESP32. The hardware engineer must choose between I2C and SPI.
Sensors to connect:
- 3× BME280 (temperature/humidity/pressure) - max 3.4 MHz
- 2× VEML7700 (ambient light) - max 400 kHz
- 1× MPU6050 (accelerometer/gyroscope) - max 400 kHz
- 1× CCS811 (air quality CO2/VOC) - max 400 kHz
- 1× SD card module for data logging - max 25 MHz
Given Data:
- ESP32 available GPIO pins: 12 general-purpose pins
- I2C requires: 2 pins (SDA, SCL) for ALL devices
- SPI requires: 3 shared pins (MOSI, MISO, SCK) + 1 CS per device
Step 1: Calculate I2C pin requirements
I2C bus: 2 pins total (SDA, SCL) All 8 devices share the same bus Total pins: 2 (extremely pin-efficient!)
Address conflicts check: - BME280 default: 0x76 or 0x77 (2 addresses available) - Need 3 BME280s, but only 2 addresses → ADDRESS CONFLICT!
Resolution: Use TCA9548A I2C multiplexer (adds 1 address, creates 8 buses) Cost: +$0.95 per board
Step 2: Calculate SPI pin requirements
SPI shared: 3 pins (MOSI, MISO, SCK) Chip select (CS) per device: 8 pins (one per sensor) Total pins: 3 + 8 = 11 pins
ESP32 has 12 available → Just barely fits!
Step 3: Calculate maximum throughput requirements
BME280 burst read: 8 bytes (all readings) at 3.4 MHz = 19 microseconds Read all 3 sensors: 19 µs × 3 = 57 µs per cycle
With I2C at 400 kHz (standard mode): BME280 read: 8 bytes × 8 bits × (1/400 kHz) = 160 µs per sensor All 3 sensors: 160 × 3 = 480 µs
Speed advantage of SPI: 480 ÷ 57 = 8.4× faster for BME280
Step 4: Calculate power consumption
I2C bus idle: Pull-up resistors constantly draw current - 4.7 kΩ pull-ups to 3.3V: I = 3.3V / 4.7kΩ = 0.7 mA continuous - 24/7 operation: 0.7 mA × 24 hr × 365 days = 6.1 Ah/year
SPI idle: No pull-ups needed, CS pins drive high - Idle current: ~0.05 mA (just GPIO leakage) - 24/7 operation: 0.05 mA × 24 hr × 365 days = 0.44 Ah/year
Decision: Use I2C with multiplexer
Rationale:
- Pin efficiency: 2 pins (+ mux) vs 11 pins (SPI)
- Throughput adequate: 480 µs read cycle meets 1 Hz sampling requirement (1000 ms budget)
- Simplified PCB routing: I2C bus can daisy-chain, SPI needs star topology for CS lines
- Standard protocol: All sensors support I2C natively
- Address conflict resolved: Mux adds $0.95 but saves 9 GPIO pins for future expansion
When to use SPI instead: If sampling rate >100 Hz (need <10 ms reads) or SD card throughput critical
Key insight: Choose I2C for many low-speed sensors (pin-constrained), SPI for few high-speed peripherals.
Decision Framework: Serial Protocol Selection Matrix
| Criterion | I2C | SPI | UART | Recommendation |
|---|---|---|---|---|
| Device count >4 | ✓ Best (2 pins total) | Poor (1 CS per device) | N/A (point-to-point) | I2C |
| Speed >1 MHz | Limited (3.4 MHz max) | ✓ Best (50+ MHz) | Slow (<115 kbps) | SPI |
| Pin-constrained (<6 GPIO) | ✓ Best (2 pins) | Poor (4+ pins) | OK (2 pins) | I2C |
| Full-duplex required | No (half-duplex) | ✓ Yes (MOSI + MISO) | ✓ Yes (TX + RX) | SPI or UART |
| Simple point-to-point | Overkill | Overkill | ✓ Perfect | UART |
| Legacy peripheral | Common | Very common | Universal | Check datasheet |
Real-world selection: | Application | Preferred Protocol | Why | |————-|——————-|—–| | Multiple sensors (temp, humidity, pressure) | I2C | 10+ devices on 2 pins | | SD card / Flash memory | SPI | Speed matters for logging | | TFT display | SPI | High-speed pixel data | | GPS module | UART | Simple serial, NMEA strings | | Bluetooth module | UART | AT command interface | | IMU sensor (MPU6050) | I2C | Low-speed, multiple addresses |
Hybrid approach (common in real designs): - I2C bus: Slow sensors (BME280, light sensors, RTCs) - SPI bus: Fast peripherals (SD card, display) - UART: External modules (GPS, Bluetooth, debug console)
Common Mistake: Forgetting I2C Pull-Up Resistors
Scenario: A beginner connected 4 I2C sensors (BME280, VEML7700, MPU6050, RTC) to an ESP32 but the code couldn’t detect any devices. Wire.begin() returned no errors, but Wire.requestFrom() always failed.
The mistake: No pull-up resistors on SDA and SCL lines
What went wrong: I2C uses open-drain outputs: - Devices can only pull the line LOW (to ground) - Devices cannot pull the line HIGH - Pull-up resistors pull the line HIGH when no device is transmitting - Without pull-ups: Line stays at ~0V (floating or pulled low)
Debug measurements: - SDA voltage with no pull-up: 0.3V (should be 3.3V when idle) - SCL voltage with no pull-up: 0.5V (should be 3.3V when idle) - I2C scanner output: No devices found (communication impossible)
Why pull-ups are needed: I2C protocol: Start condition = SDA goes LOW while SCL is HIGH - Without pull-ups, SCL never reaches HIGH - Start condition cannot be generated - Communication fails at initialization
Correct fix: Add 4.7 kΩ pull-up resistors
SDA ----[4.7kΩ]---- +3.3V
SCL ----[4.7kΩ]---- +3.3V
After adding pull-ups:
- SDA idle voltage: 3.28V ✓
- SCL idle voltage: 3.30V ✓
- I2C scanner: 4 devices found at 0x68, 0x76, 0x10, 0x57 ✓
Pull-up resistor sizing: | Bus Speed | Typical Resistor | Range | |———–|—————–|——-| | 100 kHz (Standard) | 4.7 kΩ | 2.2-10 kΩ | | 400 kHz (Fast) | 2.2 kΩ | 1-4.7 kΩ | | 1 MHz (Fast+) | 1 kΩ | 680Ω-2.2 kΩ |
Built-in pull-ups: Some sensors include on-board pull-ups (check schematic). If multiple boards on the bus, total pull-up = 1/(1/R1 + 1/R2 + …) must stay in range.
Key lesson: I2C ALWAYS needs pull-up resistors on SDA and SCL. Without them, communication is impossible. Check for on-board pull-ups before adding external ones.
42.5 Summary
This chapter explored sensor-to-microcontroller communication protocols including I2C, SPI, UART, and system-level wired and wireless connectivity options for IoT gateways.
Key Takeaways:
- Protocol bridging requires understanding timing semantics, not just message translation
- Gateway processor requirements depend on edge processing complexity
- Different protocols (I2C, SPI, UART, MQTT) have fundamentally different characteristics
- Effective gateways implement buffering, state management, and data transformation
42.7 Knowledge Check
Common Pitfalls
1. Confusing I2C Address Conflicts With Bus Faults
Most I2C sensors come with one or two fixed addresses (e.g., BME280 at 0x76 or 0x77). Adding two identical sensors to the same I2C bus causes address conflicts resulting in garbled readings that appear as sensor malfunction. Always check sensor address configurability before purchasing multiples and design bus topology to avoid conflicts.
2. Using RS-232 Cable Lengths With RS-485 Topology
RS-232 is point-to-point, limited to 15m. RS-485 is multi-drop, supporting 1200m at 100kbps. Using RS-232 connectors and assumptions for an RS-485 run creates unreliable communication at distances over 15m. Always verify the electrical standard (RS-232 vs. RS-485) from device datasheets before selecting cable and termination resistors.
3. Not Accounting for Modbus Register Byte Order
Modbus 16-bit registers can be combined into 32-bit or 64-bit values, but byte order (big-endian or little-endian) and word order are device-specific. A 32-bit float value spread across two Modbus registers may arrive in four possible byte/word orderings. Always consult the device register map documentation to determine the correct byte and word order for multi-register values.
4. Forgetting Pull-Up Resistors on I2C and 1-Wire Buses
I2C and 1-Wire are open-drain buses requiring external pull-up resistors (I2C: 2.2-10kΩ, 1-Wire: 4.7kΩ) to VCC. Without pull-ups, bus lines float high impedance and communication fails inconsistently. Many development boards include pull-ups, but custom PCBs and cable extensions require explicit pull-up resistors on each bus.
42.8 What’s Next
| If you want to… | Read this |
|---|---|
| Learn how these protocols are bridged to cloud | Protocol Bridging Fundamentals |
| Practice building a sensor protocol gateway | Gateway Protocol Translation Lab |
| See real gateways using these protocols | Real-World Gateway Examples |
| Study pub/sub patterns for sensor data | Pub/Sub and Topic Routing |
Continue to Real-World Gateway Examples to study real-world gateway architectures and protocol translation engine designs with practical implementation patterns.