Raspberry Pi IoT Capstone Project
End-to-end sensor dashboard: DHT22 → MQTT → InfluxDB → Grafana
Skills taught: embedded.iot-project
Project Architecture
This capstone project builds a complete IoT monitoring system on a single Raspberry Pi. The data flows through five stages: Sensor → Collector → MQTT → Database → Dashboard. Each stage is a separate process, communicating via standard protocols — making each component replaceable.
IoT Dashboard Architecture
──────────────────────────────────────────────
[DHT22 Sensor]
│ GPIO4 (physical pin 7)
▼
[Python Collector] sensor_collector.py
- reads DHT22 every 10s
- publishes JSON to MQTT
│ paho-mqtt
▼
[Mosquitto MQTT Broker] port 1883
- routes messages
│
▼
[Telegraf Agent] MQTT consumer plugin
- subscribes to sensor/#
- writes to InfluxDB
│ HTTP line protocol
▼
[InfluxDB 2.x] port 8086 (time-series DB)
- stores readings
│ Flux queries
▼
[Grafana] port 3000 (dashboard UI)
- live charts, alerts
- accessible from browser
Step 1: Install the Stack
# Update system
sudo apt update && sudo apt upgrade -y
# Install Mosquitto MQTT broker
sudo apt install -y mosquitto mosquitto-clients
sudo systemctl enable --now mosquitto
# Install InfluxDB 2.x (ARM64 — Pi 4/5 or Pi 3 64-bit OS)
curl -s https://repos.influxdata.com/influxdata-archive_compat.key | sudo tee /etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg
echo 'deb [signed-by=/etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg] https://repos.influxdata.com/debian stable main' | sudo tee /etc/apt/sources.list.d/influxdata.list
sudo apt update && sudo apt install -y influxdb2
sudo systemctl enable --now influxd
# Install Telegraf (InfluxDB agent)
sudo apt install -y telegraf
# Install Grafana
sudo apt install -y apt-transport-https software-properties-common wget
sudo mkdir -p /etc/apt/keyrings/
wget -q -O - https://apt.grafana.com/gpg.key | gpg --dearmor | sudo tee /etc/apt/keyrings/grafana.gpg > /dev/null
echo "deb [signed-by=/etc/apt/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
sudo apt update && sudo apt install -y grafana
sudo systemctl enable --now grafana-server
echo "Stack installed!"
echo "InfluxDB: http://$(hostname -I | awk '{print $1}'):8086"
echo "Grafana: http://$(hostname -I | awk '{print $1}'):3000"
Step 2: Python Sensor Collector
#!/home/pi/iot-dashboard/venv/bin/python
"""DHT22 sensor collector — reads every 10s, publishes to MQTT."""
import adafruit_dht
import board
import paho.mqtt.client as mqtt
import json
import time
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s'
)
DEVICE_ID = "pi-01"
BROKER = "localhost"
INTERVAL = 10 # seconds between readings
# DHT22 on GPIO4 (physical pin 7)
dht = adafruit_dht.DHT22(board.D4)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, f"collector-{DEVICE_ID}")
client.will_set(f"sensors/{DEVICE_ID}/status",
json.dumps({"online": False, "device": DEVICE_ID}), qos=1, retain=True)
client.connect(BROKER, 1883, keepalive=60)
client.loop_start()
# Announce online
client.publish(f"sensors/{DEVICE_ID}/status",
json.dumps({"online": True, "device": DEVICE_ID}), qos=1, retain=True)
logging.info(f"Collector started — device={DEVICE_ID}, interval={INTERVAL}s")
while True:
try:
temperature = dht.temperature
humidity = dht.humidity
if temperature is not None and humidity is not None:
payload = {
"device": DEVICE_ID,
"temperature": round(float(temperature), 1),
"humidity": round(float(humidity), 1),
"ts": int(time.time())
}
topic = f"sensors/{DEVICE_ID}/data"
client.publish(topic, json.dumps(payload), qos=1)
logging.info(f"Published: {payload}")
else:
logging.warning("DHT22 returned None — skipping")
except RuntimeError as e:
logging.warning(f"DHT read error: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
time.sleep(INTERVAL)
Step 3: Configure Telegraf to Bridge MQTT → InfluxDB
# /etc/telegraf/telegraf.d/mqtt-sensors.conf
[[inputs.mqtt_consumer]]
servers = ["tcp://localhost:1883"]
topics = ["sensors/+/data"]
qos = 1
data_format = "json"
# Map JSON fields to InfluxDB tags and fields
json_string_fields = ["device"]
tag_keys = ["device"]
# Measurement name in InfluxDB
name_override = "environment"
[[outputs.influxdb_v2]]
urls = ["http://localhost:8086"]
token = "YOUR_INFLUXDB_TOKEN" # from InfluxDB UI → Load Data → API Tokens
org = "home"
bucket = "sensors"
Step 4: Deploy as systemd Service
# Create project and virtual environment
mkdir -p /home/pi/iot-dashboard
cd /home/pi/iot-dashboard
python3 -m venv venv
source venv/bin/activate
pip install adafruit-circuitpython-dht paho-mqtt adafruit-blinka
# Copy sensor_collector.py here
cp sensor_collector.py /home/pi/iot-dashboard/
# Create systemd service
sudo tee /etc/systemd/system/sensor-collector.service << 'EOF'
[Unit]
Description=DHT22 Sensor Collector
After=network.target mosquitto.service
Wants=mosquitto.service
[Service]
Type=simple
User=pi
Group=pi
WorkingDirectory=/home/pi/iot-dashboard
ExecStart=/home/pi/iot-dashboard/venv/bin/python sensor_collector.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now sensor-collector.service
sudo systemctl enable --now telegraf
# Check everything is running
for svc in mosquitto influxd telegraf sensor-collector grafana-server; do
echo -n "$svc: "
systemctl is-active $svc
done
Tip: Open Grafana at http://your-pi-ip:3000 (default login: admin/admin — change immediately). Add InfluxDB as a data source (Connections → Data sources → InfluxDB, Flux language). Create a new dashboard with a Time series panel using this Flux query: `from(bucket: "sensors") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "environment") |> filter(fn: (r) => r._field == "temperature")`
Warning: InfluxDB 2.x and Grafana each require ~200–400 MB RAM at idle. The full stack (Mosquitto + InfluxDB + Telegraf + Grafana) needs a Raspberry Pi 3B or Pi 4 with ≥1 GB RAM. On a Pi Zero W (512 MB RAM), only run Mosquitto + the Python collector — use a separate machine for InfluxDB and Grafana.
Frequently Asked Questions
Can a Raspberry Pi Zero W run this full stack?
Only partially. The Pi Zero W (1 core, 512 MB RAM) can handle the Python sensor collector and Mosquitto broker. InfluxDB + Grafana together need ~400–800 MB RAM and Pi 3 or Pi 4. For a Zero W deployment, run only Mosquitto on the Pi and use a cloud InfluxDB + Grafana instance.
How do I add Grafana alerting to get notified when temperature spikes?
In Grafana: open the panel → Edit → Alert tab → Create alert rule. Set threshold (e.g., temperature > 30°C for 2 minutes). Configure a notification channel (Alerting → Contact points) for Telegram, Email, Slack, or PagerDuty. Grafana evaluates the alert every 10–60 seconds and sends notifications on state change.
How much disk space does InfluxDB use over time?
With 10-second readings and 2 fields: ~100 MB per year per sensor after compression. InfluxDB 2.x supports retention policies per bucket (Buckets → Edit → Set retention period) to automatically delete data older than N days, keeping disk usage bounded.