Skip to content
You Start with one site
Amounts in Start with one site
Capstone · IoT & AIoT

Build a live environment monitor that reports over MQTT.

An ESP32 reads temperature and humidity and publishes them every 30 seconds to an MQTT broker you run. By the end the readings arrive on your computer as they happen, and a command from you switches a relay on the board.

⏱️ About a weekend 🎓 Beginner-friendly ◉ Reports live over MQTT

What you end with

A sensor node that reports a fresh reading every 30 seconds and obeys a command, built on open MQTT, so it works with any broker. If you want a record and alerts when nobody is watching, the last step shows two ways to keep them.

📟 Senseread the sensor ☁️ Reportto the broker 📱 Decideyou, or a rule ⚡ Actswitch the relay THE LIVE LOOP
● reads & reports up● decides & commands back

What you need

Get the parts wherever suits you: a local electronics shop, or online. Pick a shop and each Find it link searches there.

An ESP32 dev boardAny ESP32; WiFi is built in, no gateway.Find it
A BME280 sensorTemperature + humidity over I2C. A DHT22 works too.Find it
Jumper wires + USB cableFour wires: 3V3, GND, SDA, SCL.Find it
An MQTT brokerMosquitto, free and open source, on any computer on the same Wi-Fi.

Concepts you'll use

You do not need to read these first. Open one only when a step needs it.

Build it

Build track
Follow this build, one step at a time

Tick each step as you finish it. Your place is kept, so you can stop and come back.

1

Wire the sensor

The BME280 talks over I2C, so it takes four wires. On a standard ESP32 the I2C pins are GPIO 21 (SDA) and GPIO 22 (SCL).

  • BME280 VCC → ESP32 3V3
  • BME280 GND → ESP32 GND
  • BME280 SDA → ESP32 GPIO 21
  • BME280 SCL → ESP32 GPIO 22

New to I2C wiring? Read the I2C sensor lesson, then come back.

2

Run a broker

Install Mosquitto on a computer on the same Wi-Fi. Since version 2 it listens only to its own computer until you allow more, so for a first run on a home network add two lines to mosquitto.conf and restart it:

listener 1883
allow_anonymous true

Then find that computer's address on your network (for example 192.168.1.20). Before the node leaves your desk, give the broker passwords and TLS; the broker setup lesson shows how.

3

Flash the firmware

This publishes a JSON reading to the telemetry topic d/node-1/t every 30 seconds. Set your Wi-Fi details and your broker's address, then flash it from the Arduino IDE.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <Adafruit_BME280.h>

// --- your Wi-Fi ---
const char* WIFI_SSID = "your-network";
const char* WIFI_PASS = "your-password";

// --- your MQTT broker ---
#define USE_TLS 0                             // 1 for a broker on port 8883
const char* MQTT_HOST = "192.168.1.20";       // the computer that runs Mosquitto
const int   MQTT_PORT = 1883;                 // 8883 with TLS
const char* DEVICE_ID = "node-1";             // names this device and its topics
const char* MQTT_USER = "";                   // empty if the broker has no login
const char* MQTT_PASS = "";

#if USE_TLS
WiFiClientSecure net;
#else
WiFiClient net;
#endif
PubSubClient     mqtt(net);
Adafruit_BME280  bme;

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  bme.begin(0x76);                 // BME280 on I2C (SDA=21, SCL=22)
#if USE_TLS
  net.setInsecure();               // fine for a first run; use setCACert() in production
#endif
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
}

void loop() {
  if (!mqtt.connected()) {
    // client id, username, password (no login when the username is empty)
    if (MQTT_USER[0]) mqtt.connect(DEVICE_ID, MQTT_USER, MQTT_PASS);
    else              mqtt.connect(DEVICE_ID);
  }
  mqtt.loop();

  char payload[64];
  snprintf(payload, sizeof(payload),
           "{\"temperature\":%.1f,\"humidity\":%.1f}",
           bme.readTemperature(), bme.readHumidity());
  Serial.println(payload);         // the reading, even with no network

  String topic = String("d/") + DEVICE_ID + "/t";   // the telemetry topic
  mqtt.publish(topic.c_str(), payload);

  delay(30000);                    // one reading every 30 s
}

The first lines name everything about the broker in one place, so moving the node to another broker later means changing those lines and nothing else.

4

Watch it arrive

Open the Serial Monitor: each reading prints there first. Then, on the computer that runs the broker, subscribe to every topic of the node:

mosquitto_sub -h localhost -t 'd/node-1/#' -v

A line arrives every 30 seconds. If nothing comes, the usual causes are a wrong broker address, a firewall that blocks port 1883, or Wi-Fi that needs a captive-portal login. The MQTT client lesson covers reconnect and offline buffering for a node you can trust.

You're done when

  • The Serial Monitor prints a temperature and humidity reading every thirty seconds.
  • The same readings arrive in mosquitto_sub on your computer.
  • Breathe on the sensor, and within a minute the humidity climbs, then settles. That is your own data, end to end.

Make it act, not just report

The same connection runs the other way. Have your device subscribe to its command topic and act on what arrives there, so you can flip a relay, a pump, or a fan from another computer.

Subscribe tod/<device-id>/c Command{"command":"relay","value":true}

Add a handler to the same firmware:

#include <ArduinoJson.h>

const int RELAY_PIN = 26;               // the GPIO that drives your relay

// runs whenever a command arrives on d/<id>/c
void onCommand(char* topic, byte* data, unsigned int len) {
  StaticJsonDocument<128> msg;
  if (deserializeJson(msg, data, len)) return;   // ignore anything malformed
  if (msg["command"] == "relay") {
    digitalWrite(RELAY_PIN, msg["value"] ? HIGH : LOW);
  }
}

void setup() {
  // ... the same Wi-Fi + MQTT setup as before ...
  pinMode(RELAY_PIN, OUTPUT);
  mqtt.setCallback(onCommand);          // wire the handler in
}

// and once you are connected, subscribe to your command topic:
//   mqtt.subscribe((String("d/") + DEVICE_ID + "/c").c_str());

Then send it a command from the broker's computer, and the pin switches:

mosquitto_pub -h localhost -t d/node-1/c -m '{"command":"relay","value":true}'
But why send it to the cloud at all, if the board can switch a relay by itself? For anything simple and fast, you should not. A fixed timer, a debounce, or a thermostat loop belongs in firmware, offline, with no network to depend on and nothing to bill. The cloud earns its place by doing what a lone microcontroller cannot do, or cannot do reliably:
  • Tell the right people, reliably. A board with a GSM module can fire off an SMS, true. But getting the right alert to the right people, with escalation when no one answers, retries, delivery confirmation, and a contact list you can change without reflashing, is a different problem, and the one that matters at 2am.
  • Notice its own failure. A device that has gone silent can't run code to say so. Only a watchdog outside the device catches "this sensor stopped reporting," the failure you most need to know about.
  • Coordinate many devices. "Freezer door open and temperature rising" needs two devices talking; "apply this to all 40 sensors tagged Greenhouse-B" needs a fleet.
  • Keep an audit trail. An immutable, timestamped log of every breach and who acknowledged it, one that survives the device being replaced.
  • Change behaviour without reflashing. Edit a rule in a web form in thirty seconds, no firmware risk, no embedded engineer needed.
So the local loop keeps running with or without a connection; the cloud is the oversight layer on top, not the control loop.

Optional last step: keep the record and get alerts

Your build is finished. If the node will stay on a real machine or room, the readings are worth keeping, and a silent node is worth knowing about. Two ways, and the firmware is the same for both:

A

On your own broker

Keep Mosquitto, and add a database and a chart beside it: Telegraf writes each reading to InfluxDB, Grafana draws it and sends the alert. The production monitoring lesson builds exactly this.

B

On a hosted service

Send the same readings to siliconwit.io, our monitoring service, which keeps the record, raises the alert and can give the node a public page. Add a device there (Add Device, then Define my own device, with the fields temperature and humidity), and change the broker lines of the firmware:

USE_TLS1 MQTT_HOSTmqtt.siliconwit.io MQTT_PORT8883 DEVICE_ID, MQTT_USERyour Device ID, e.g. SWD-R7N4WX MQTT_PASSyour Access Token

The topics stay d/<device-id>/t and d/<device-id>/c. It works with any MQTT client, so to leave, change the same lines back to your own broker.

Take it further

The same node is the seed of every bigger build: add a soil-moisture probe and you have the greenhouse monitoring capstone; add a threshold and you get alerts before something fails; run a tiny model on the board and only report anomalies with edge-AI predictive maintenance.

References

Found this useful?