The most robust Raspberry Pi use cases in embedded engineering have shifted far beyond desktop media centers. In 2026, the premier application for these boards is the Industrial IoT (IIoT) edge gateway—aggregating local sensor data, processing it, and publishing it to an MQTT broker for cloud ingestion. This architecture offloads network overhead from low-power microcontrollers and centralizes telemetry.
This guide walks through building a hardwired IIoT temperature gateway using the Raspberry Pi 5. We will bypass heavy abstraction libraries, read raw I2C registers from a Microchip MCP9808 precision sensor, and publish the data using the modern Paho MQTT v2.0 API.
The Shift in Raspberry Pi Use Cases: From Hobby Desk to Edge Gateway
When evaluating Raspberry Pi use cases for professional or prosumer environments, the Pi 5’s PCIe Gen 2 lane and upgraded Cortex-A76 cores make it a viable edge compute node. Unlike an ESP32, which handles single-point telemetry, the Pi 5 can manage dozens of I2C/SPI sensors, run local SQLite databases, and execute Docker containers for edge AI inference simultaneously.
Parts List & Exact Variants
| Component | Exact Variant / Model | Approx. Cost (2026) | Notes |
|---|---|---|---|
| Single Board Computer | Raspberry Pi 5 (8GB RAM) | $80.00 | 8GB recommended for Docker/Edge AI overhead. |
| Temperature Sensor | Adafruit MCP9808 I2C Breakout (PID 1782) | $9.50 | Includes 3.3V LDO and 10k pull-ups. ±0.25°C accuracy. |
| Storage | Samsung PRO Endurance 64GB microSD | $14.00 | High endurance required for 24/7 MQTT logging. |
| Power Supply | Official Raspberry Pi 27W USB-C PD | $12.00 | Required to prevent brownouts under peripheral load. |
| Wiring | 28 AWG Silicone Jumper Wires (F-F) | $6.00 | Silicone insulation resists heat in enclosures. |
Hardware Assembly and Pin Mapping
The Raspberry Pi 5 maintains the standard 40-pin GPIO header layout, but its I2C bus characteristics are slightly faster. The MCP9808 breakout operates strictly at 3.3V logic, which aligns perfectly with the Pi’s native GPIO levels. Do not use 5V I2C sensors without a bidirectional logic level converter (like the BSS138), or you will fry the Pi 5’s SoC.
Pin Mapping Table
| Pi 5 GPIO Pin (Physical) | Pi 5 Function | MCP9808 Breakout Pin | Wire Color (Standard) |
|---|---|---|---|
| Pin 1 | 3.3V Power | VIN (or 3Vo) | Red |
| Pin 6 | Ground (GND) | GND | Black |
| Pin 3 (GPIO 2) | I2C SDA | SDA | Blue |
| Pin 5 (GPIO 3) | I2C SCL | SCL | Yellow |
Assembly Steps
- Flash the OS: Use Raspberry Pi Imager to install Raspberry Pi OS Lite (64-bit, Bookworm). Enable SSH and set your local Wi-Fi or Ethernet credentials in the advanced settings.
- Enable I2C: Boot the Pi, SSH in, and run
sudo raspi-config. Navigate to Interface Options > I2C and enable it. Reboot. - Wire the Sensor: Connect the four pins according to the mapping table above. Keep I2C traces under 30cm (1 foot) to avoid capacitance-induced signal degradation.
- Verify Address: Run
i2cdetect -y 1. You should see18in the grid, confirming the MCP9808's default 0x18 address.
Python MQTT Gateway Code (Raspberry Pi 5)
This code targets the Raspberry Pi 5 (8GB) running a 64-bit Linux kernel. We use smbus2 for direct I2C register manipulation and paho-mqtt (v2.0 API) for network transport. This avoids the bloat of hardware-abstraction layers, giving you precise control over bus timing and error handling.
Install dependencies first:
sudo apt install python3-pip python3-smbus2
pip3 install paho-mqtt --break-system-packages
#!/usr/bin/env python3
"""
IIoT Edge Gateway: MCP9808 to MQTT
Target: Raspberry Pi 5 (64-bit Bookworm)
"""
import smbus2
import paho.mqtt.client as mqtt
import time
import sys
import logging
# --- Pin & Bus Definitions ---
I2C_BUS = 1
SENSOR_ADDR = 0x18
TEMP_REGISTER = 0x05
CONFIG_REGISTER = 0x01
# --- MQTT Configuration ---
MQTT_BROKER = "192.168.1.100"
MQTT_PORT = 1883
MQTT_TOPIC = "factory/line1/ambient_temp"
QOS_LEVEL = 1 # 1 = At least once delivery
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# --- Paho MQTT v2.0 Callbacks ---
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
logging.info("Connected to MQTT Broker successfully.")
else:
logging.error(f"MQTT Connection failed with code: {reason_code}")
sys.exit(1)
def on_publish(client, userdata, mid, reason_code, properties):
logging.debug(f"Published message ID: {mid}")
# Initialize MQTT Client (Paho v2.0 API)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="pi5_edge_gateway_01")
client.on_connect = on_connect
client.on_publish = on_publish
try:
client.connect(MQTT_BROKER, MQTT_PORT, keepalive=60)
client.loop_start()
except Exception as e:
logging.critical(f"Failed to connect to MQTT broker: {e}")
sys.exit(1)
# --- I2C Sensor Reading Logic ---
def read_temperature_celsius():
try:
with smbus2.SMBus(I2C_BUS) as bus:
# Read 2 bytes from the Ambient Temperature Register (0x05)
data = bus.read_i2c_block_data(SENSOR_ADDR, TEMP_REGISTER, 2)
upper = data[0]
lower = data[1]
# Clear alert/limit flags (bits 15-13)
upper = upper & 0x1F
# Calculate temperature
temp = (upper * 16.0) + (lower / 16.0)
# Check sign bit (bit 12) for negative temperatures
if upper & 0x10:
temp -= 256.0
return round(temp, 2)
except OSError as e:
logging.error(f"I2C Bus Error: {e}")
return None
def main():
logging.info("Starting IIoT Edge Gateway loop...")
while True:
temp_c = read_temperature_celsius()
if temp_c is not None:
# Publish to MQTT
msg_info = client.publish(MQTT_TOPIC, payload=str(temp_c), qos=QOS_LEVEL)
if msg_info.rc != mqtt.MQTT_ERR_SUCCESS:
logging.warning(f"MQTT publish failed, rc={msg_info.rc}")
else:
logging.info(f"Published: {temp_c}°C to {MQTT_TOPIC}")
else:
logging.warning("Skipping publish due to I2C read failure.")
# Sleep for 5 seconds (adjust based on Nyquist requirements of your thermal mass)
time.sleep(5)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logging.info("Gateway stopped by user.")
client.loop_stop()
client.disconnect()
sys.exit(0)
Debugging I2C and MQTT Failures
When deploying Raspberry Pi use cases in industrial or remote environments, network and bus failures are inevitable. Here is how to diagnose the two most common fatal errors this script will throw.
Error 1: OSError: [Errno 121] Remote I/O error
This is the universal Linux I2C failure string. It means the kernel sent a clock pulse, but the sensor did not acknowledge (ACK) the address or data byte.
- Cause 1 (Most Likely): SDA and SCL wires are physically swapped. The Pi is sending data on the clock line, and the sensor is ignoring it.
- Cause 2: Missing pull-up resistors. If you are using a raw MCP9808 chip instead of the Adafruit breakout, you must add 4.7kΩ resistors from SDA and SCL to 3.3V. The Pi's internal pull-ups (approx 50kΩ) are too weak for reliable I2C communication at 100kHz+.
- Cause 3: The sensor has entered a low-power shutdown mode and missed the start condition. (The code above avoids this by not writing to the config register to trigger shutdown, but hardware glitches can cause it).
Error 2: FileNotFoundError: [Errno 2] No such file or directory: '/dev/i2c-1'
The Python script cannot find the I2C device node in the Linux filesystem.
- Cause 1: The I2C interface is disabled in the device tree. Run
sudo raspi-configand enable it. - Cause 2: You are running the script on a compute module or custom board where the primary I2C bus is mapped to
/dev/i2c-0or/dev/i2c-10. Checkls /dev/i2c*to verify the bus number.
1. Run
i2cdetect -y 1 in the terminal. If the grid is empty or shows all UU, your hardware wiring or pull-ups are faulty.2. Verify physical pinout continuity with a multimeter. Measure from the Pi header to the sensor breakout pins directly.
3. Check MQTT broker reachability. Run
ping 192.168.1.100 and test the port with mosquitto_pub -h 192.168.1.100 -t test -m "hello" to isolate network firewalls from Python code errors.
Extending and Simplifying the Build
Depending on your specific deployment environment, you may need to scale this architecture up or down.
How to Extend the Build
- Multi-Sensor Multiplexing: The I2C bus supports up to 127 devices, but address collisions occur. Add a TCA9548A I2C Multiplexer to run up to 8 separate MCP9808 sensors (all set to address 0x18) on a single Pi I2C bus.
- Edge AI Inference: Utilize the Pi 5’s PCIe Gen 2 lane by adding a Hailo-8L M.2 AI accelerator HAT. You can run local anomaly detection on the temperature data before publishing to MQTT, saving bandwidth.
- Cellular Fallback: Add a Quectel EC25 LTE modem via USB. Use NetworkManager to prioritize Ethernet, but automatically route MQTT traffic over LTE if the local factory switch drops.
How to Simplify the Build
- Downgrade to Pi Zero 2 W: If you only need to poll one sensor every 60 seconds and don't need Docker, the Pi Zero 2 W ($15) handles this Python script effortlessly, cutting BOM cost and power draw by 70%.
- Drop MQTT for HTTP: If your backend is a simple REST API (like a generic webhook), replace the Paho MQTT library with Python’s built-in
urllib.requestto eliminate the need for a dedicated MQTT broker entirely.
FAQ: Common Questions on Raspberry Pi Use Cases
What are the most reliable industrial Raspberry Pi use cases for 24/7 operation?
The most reliable use cases avoid heavy write-cycles to the SD card. Data logging directly to a local SQLite database on a standard microSD card will kill the flash memory in 6 to 12 months. For 24/7 operation, use a high-endurance SD card (like the Samsung PRO Endurance), mount the root filesystem as read-only using overlayroot, and stream all telemetry directly to RAM or a networked database. Alternatively, boot the Pi 5 directly from an NVMe SSD via the PCIe HAT to eliminate SD card failure modes entirely.
Can Raspberry Pi use cases replace commercial PLCs in factory automation?
No, not for safety-critical or hard-real-time control. A Raspberry Pi runs a general-purpose Linux kernel, which is not deterministic; a background garbage collection cycle or kernel interrupt can delay a GPIO toggle by milliseconds, which is unacceptable for high-speed motion control or safety interlocks. However, the Pi excels as a supervisory node (SCADA edge gateway) that reads PLC data via Modbus TCP or OPC-UA and translates it to MQTT for the IT network. Leave the real-time machine control to the Beckhoff or Allen-Bradley PLCs, and use the Pi for the data pipeline.
Which Raspberry Pi use cases require an active cooler versus passive heatsinks?
Any Raspberry Pi use case that involves sustained CPU loads above 20% (such as running local LLMs, compiling code, or processing high-framerate OpenCV video streams) requires the official Active Cooler. The Pi 5 will aggressively thermal throttle at 80°C and hard-shut down at 85°C. For light IIoT gateway tasks—like the Python MQTT script above, which uses less than 2% CPU—a simple passive aluminum heatsink or even the bare SoC in a well-ventilated enclosure is sufficient. Always monitor your thermal state in production using vcgencmd measure_temp.






