Build an IoT Sensor Network with MQTT and Raspberry Pi
IoT Networking

Build an IoT Sensor Network with MQTT and Raspberry Pi

📅 2024-01-10 RaspControl Team 35 min read
Time
35 min
Difficulty
Intermediate
Hardware
Pi 3/4/5
Language
Python
Code
GitHub ✓
← Back to Tutorials

MQTT (Message Queuing Telemetry Transport) is the backbone of most IoT systems. It's lightweight, fast, and works perfectly on Raspberry Pi. In this tutorial, you'll set up a complete sensor network that publishes real-time data to a dashboard.

IoT sensors
DHT22 temperature/humidity sensor connected to Raspberry Pi

Architecture Overview

Our system has three components: Sensor Nodes (Pi with sensors that publish data), MQTT Broker (Mosquitto running on Pi, routes messages), and Dashboard (Node-RED or Grafana to visualize data).

Install Mosquitto MQTT Broker

pi@raspberrypi:~ $
$ sudo apt update && sudo apt install -y mosquitto mosquitto-clients $ sudo systemctl enable mosquitto $ sudo systemctl start mosquitto ✓ Mosquitto MQTT broker running on port 1883

Python Sensor Publisher

import paho.mqtt.client as mqtt import Adafruit_DHT import time, json # MQTT setup client = mqtt.Client() client.connect("localhost", 1883) while True: # Read DHT22 sensor on GPIO pin 4 humidity, temp = Adafruit_DHT.read_retry( Adafruit_DHT.DHT22, 4 ) if humidity is not None: payload = json.dumps({ "temperature": temp, "humidity": humidity }) client.publish("home/sensors/bedroom", payload) time.sleep(30)
💡 Test Your MQTT Setup

Use the mosquitto_sub command to listen for messages: mosquitto_sub -t "home/sensors/#" -v

Found this helpful? Share it! 👇