Day 5 of 5
⏱ ~60 minutes
Raspberry Pi in 5 Days — Day 5

IoT and Cloud Integration

Your Pi can push data to the cloud, receive remote commands, and integrate with dashboards and automation platforms. Today you'll build the full IoT pipeline.

MQTT Protocol

MQTT (Message Queue Telemetry Transport) is the standard protocol for IoT devices. Lightweight, publish/subscribe model, works over TCP. Devices publish messages to topics (home/pi/temperature). Other devices or servers subscribe to topics and receive messages. A broker (e.g., Mosquitto, HiveMQ, AWS IoT) routes messages between publishers and subscribers. The Pi publishes sensor data; your phone subscribes to receive it.

Node-RED for Visual Automation

Node-RED is a visual programming tool that runs on the Pi (or in the cloud). Connect sensor inputs to processing logic to outputs using a drag-and-drop interface. Built-in nodes: HTTP, MQTT, email, Telegram, InfluxDB, and hundreds of third-party nodes. Build automation flows without writing code: 'when temperature > 30, send Telegram message and turn on fan GPIO'. Install with: bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

Cloud Dashboards

Grafana + InfluxDB is the standard IoT time-series stack. InfluxDB stores time-series sensor data. Grafana visualizes it with professional dashboards — heatmaps, gauges, graphs, alerts. Both run on the Pi for local use or on a cloud VM for remote access. Alternatively, use Adafruit IO (free tier: 30 data points/minute, 5 feeds) for a hosted solution that requires zero server management.

python
#!/usr/bin/env python3
# MQTT publisher: Pi sends sensor data to a broker
# pip3 install paho-mqtt adafruit-circuitpython-dht

import json, time, board, adafruit_dht
import paho.mqtt.client as mqtt

# Configure
BROKER  = 'localhost'    # or 'broker.hivemq.com' for public test broker
PORT    = 1883
TOPIC   = 'home/pi/sensors'
DEVICE  = 'pi-living-room'

client = mqtt.Client(client_id=DEVICE)
client.connect(BROKER, PORT, keepalive=60)
client.loop_start()

dht = adafruit_dht.DHT22(board.D4, use_pulseio=False)

print(f"Publishing to {BROKER}:{PORT}/{TOPIC}")
try:
    while True:
        try:
            payload = json.dumps({
                'device':   DEVICE,
                'ts':       time.time(),
                'temp_c':   round(dht.temperature, 1),
                'humidity': round(dht.humidity, 1),
            })
            result = client.publish(TOPIC, payload, qos=1)
            result.wait_for_publish()
            print(f"Published: {payload}")
        except RuntimeError:
            print("DHT read error, retrying...")
        time.sleep(30)
except KeyboardInterrupt:
    client.loop_stop()
    client.disconnect()
    dht.exit()
    print("Disconnected.")
💡
Use QoS level 1 for sensor data (qos=1) — MQTT guarantees the message is delivered at least once. QoS 0 is fire-and-forget (data loss is possible). QoS 2 guarantees exactly-once delivery but is slower. For sensor data, QoS 1 is the right balance.
📝 Day 5 Exercise
Build the Full IoT Pipeline
  1. Install Mosquitto MQTT broker on the Pi: sudo apt install mosquitto mosquitto-clients. Test with mosquitto_pub -t test -m hello and mosquitto_sub -t test in another terminal.
  2. Run the MQTT publisher script. Subscribe in a second terminal: mosquitto_sub -t home/pi/sensors. Verify you see JSON messages.
  3. Install Node-RED. Create a flow: MQTT input node → JSON parse → function node to extract temperature → debug output. Trigger on real sensor data.
  4. Sign up for a free Adafruit IO account. Create a feed called 'temperature'. Modify the publisher to also send data to io.adafruit.com using your API key. View the live chart on Adafruit IO.
  5. Set up an alert: in Node-RED, add a condition node that sends an email (via Gmail SMTP node) when temperature exceeds your threshold.

Day 5 Summary

  • MQTT is the IoT standard: lightweight, pub/sub, works on 2G networks; QoS 1 for reliable delivery
  • Node-RED enables visual automation without code — connect MQTT to email, Telegram, databases
  • InfluxDB+Grafana is the professional time-series stack; Adafruit IO is the easiest hosted option
  • The complete IoT pipeline: sensor → Pi → MQTT → broker → subscriber → database → dashboard → alert
Challenge

Implement two-way control: subscribe to a command topic (home/pi/commands) and handle JSON commands like {"pin":18,"state":"on"} to control GPIO pins remotely. This turns your Pi into a remotely-controllable device. Add authentication (MQTT username/password) so only you can send commands.

Finished this lesson?