IoT with Raspberry Pi and MQTT: Building a Real-Time Sensor Network
Step-by-step guide to building a real-time sensor network using Raspberry Pi as gateway, Mosquitto as MQTT broker, and Python to store and visualise sensor data.
IoT with Raspberry Pi and MQTT: Building a Real-Time Sensor Network
A Raspberry Pi running Mosquitto as an MQTT broker, connected to a fleet of ESP32 sensor nodes, feeding data into a Python backend and live dashboard — this is a practical IoT stack you can build with inexpensive hardware and open-source software. Here is how to build it from scratch.
Hardware You Need
- Raspberry Pi 4 (2GB RAM minimum) or Raspberry Pi 3B+
- One or more ESP32 development boards
- Sensors: DHT22 for temperature/humidity, capacitive soil moisture sensor, BH1750 for light
- MicroSD card (16GB+) for the Pi, jumper wires and breadboard for prototyping
Raspberry Pi Setup
Flash Raspberry Pi OS Lite (64-bit) to your SD card using Raspberry Pi Imager. Enable SSH and configure your Wi-Fi credentials in the Imager settings before flashing so you can connect headlessly.
Install Mosquitto:
sudo apt update && sudo apt install -y mosquitto mosquitto-clients python3-pip
sudo systemctl enable mosquitto
pip3 install paho-mqtt flask sqlalchemyConfigure Mosquitto with authentication (never run an open MQTT broker on a network):
sudo mosquitto_passwd -c /etc/mosquitto/passwd iot_user# /etc/mosquitto/conf.d/default.conf
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwdESP32 Firmware (Arduino C++)
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>const char WIFI_SSID = "YOUR_SSID";
const char WIFI_PASSWORD = "YOUR_PASSWORD";
const char MQTT_SERVER = "192.168.1.x"; // Pi IP
const char MQTT_USER = "iot_user";
const char MQTT_PASSWORD = "yourpassword";
const char DEVICE_ID = "node_01";
#define DHT_PIN 4
#define SOIL_PIN 34
WiFiClient espClient;
PubSubClient mqtt(espClient);
DHT dht(DHT_PIN, DHT22);
void publishReadings() {
float temp = dht.readTemperature();
float humidity = dht.readHumidity();
int rawSoil = analogRead(SOIL_PIN); float moisture = map(rawSoil, 4095, 1500, 0, 100); if (isnan(temp)) return; String payload = "{\"device\":\"" + String(DEVICE_ID) + "\"," "\"temp\":" + String(temp,1) + "," "\"humidity\":" + String(humidity,1) + "," "\"moisture\":" + String(moisture,1) + "}"; mqtt.publish(("farm/field/1/" + String(DEVICE_ID) + "/sensors").c_str(), payload.c_str());}