Connecting the Machine with MQTT
Send the machine’s temperature and vibration to an MQTT broker every five seconds and switch its cooling fan remotely — from a browser, or from another team’s computer.
- Duration
- 90 minutes
- IoT layer
- Connectivity layer: Wi-Fi and MQTT
- Libraries
DHT sensor library for ESPxPubSubClient- Internet connection required
- Internet connection required
What you will learn
- Explain the publish/subscribe model and the role of the MQTT broker
- Design a clear topic structure for production data (company/line/machine/value)
- Connect an ESP32 to Wi-Fi and to an MQTT broker
- Publish sensor values and react to incoming commands
- Diagnose common connection and topic errors
Open in Wokwi
No installation, no hardware. Open a new ESP32 project in the free Wokwi simulator, then:
- Paste sketch.ino into the sketch.ino tab and replace the whole content of the diagram.json tab with our diagram.json.
- Add the libraries: open the Library Manager tab and add each library from libraries.txt (or create a libraries.txt file and paste the list).
- Press the green Start button and watch the Serial Monitor.
Wiring
The same circuit is used in all three exercises. The diagram.json file below builds it in Wokwi for you.
| Component (Wokwi part) | Component pin | ESP32 pin | Role in the scenario |
|---|---|---|---|
| DHT22 temperature/humidity sensor | VCC / SDA / GND | 3V3 / GPIO 15 / GND | Motor temperature |
| Potentiometer | VCC / SIG / GND | 3V3 / GPIO 34 / GND | Machine vibration level (0–100 %) |
| Red LED + 220 Ω resistor | Anode (via resistor) / Cathode | GPIO 2 / GND | Alarm lamp |
| Relay module | VCC / IN / GND | 5V / GPIO 5 / GND | Cooling fan switch |
Step by Step
A machine monitor that only works on the spot cannot be supervised from the control room. In this exercise you connect the smart machine monitor from Exercise 1 to the network:
- every 5 seconds the ESP32 publishes the temperature and the vibration to an MQTT broker,
- it subscribes to a command topic and switches the cooling fan when ON or OFF arrives,
- you watch and control your machine — and other teams’ machines — from a browser.
MQTT is the most widely used messaging protocol in industrial IoT: it is lightweight, reliable and runs on very small devices. Devices never talk to each other directly — they all talk to the broker, which forwards every message to everyone who subscribed to its topic.
These are the topics of team01:
| Topic | Direction | Payload example |
|---|---|---|
smartvet/team01/line1/temperature |
ESP32 → broker (publish) | 36.4 |
smartvet/team01/line1/vibration |
ESP32 → broker (publish) | 72 |
smartvet/team01/line1/fan |
broker → ESP32 (subscribe) | ON / OFF |
Prepare the Wokwi project
The circuit is the same as in Exercise 1. If you saved Exercise 1 in Wokwi, make a copy of it; otherwise open a new ESP32 project and paste our diagram.json.
- Paste the new sketch.ino from the code section below.
- In the Library Manager, add PubSubClient — you now need two libraries (see libraries.txt).
- Find this line and replace
team01with your own team ID (team02, team03 …):
const char* TEAM = "team01"; // every team uses its own IDIf two teams use the same ID, they will control each other’s fans.
Understand the code
Wi-Fi. Wokwi simulates an open access point called Wokwi-GUEST. Giving the channel (6) skips the network scan and saves a few seconds:
WiFi.begin(WIFI_SSID, WIFI_PASS, 6);Topics. All topics are built from one base, so changing TEAM changes all of them:
String base = "smartvet/" + String(TEAM) + "/line1/";
topicTemp = base + "temperature";Connecting to the broker. connectMQTT() tries again every two seconds until the broker accepts the connection, then subscribes to the fan topic. The client ID gets a random suffix, because a broker allows only one connection per ID.
The callback. onMessage() runs automatically whenever a message arrives on a subscribed topic. It turns the bytes into text and switches the relay:
if (msg == "ON") digitalWrite(RELAY_FAN, HIGH);
if (msg == "OFF") digitalWrite(RELAY_FAN, LOW);The loop. mqtt.loop() must run all the time — it keeps the connection alive and delivers incoming messages. Instead of delay(), a millis() timer publishes every 5 seconds, so the ESP32 can keep listening in between.
Watch the data flow and send commands
Start the simulation. The Serial Monitor shows the Wi-Fi connection, the broker connection and then a Published: … line every five seconds.
Now open the HiveMQ WebSocket Client in a new browser tab: hivemq.com/demos/websocket-client.
- Check that Host is
broker.hivemq.comand click Connect. - Click Add New Topic Subscription, enter
smartvet/team01/#(with your team ID) and click Subscribe. - Watch the Messages area: your temperature and vibration values arrive every five seconds. Change the DHT22 and the potentiometer in Wokwi and see the new values appear.
- In the publish area, enter the topic
smartvet/team01/line1/fan, the messageONand click Publish. The Serial Monitor printsCommand received…and the relay switches. SendOFFto switch it back.
Follow one value on its way: sensor → ESP32 → Wi-Fi → broker → browser. And a command the other way: browser → broker → ESP32 → relay.
Challenge tasks
- Publish the humidity on a new topic
…/line1/humidity. - Publish a status message (
OKorALARM) on…/line1/status— but only when the alarm state changes, not every five seconds. - Change the publishing interval to 10 seconds. What do you gain, what do you lose? Think about fresh data versus network load.
- Teamwork: subscribe to another team’s topics, monitor their machine and send their fan an
ONcommand when it overheats.
Find the bug
Two typical faults. With each one the data still arrives in the browser — but the fan no longer reacts to commands. Find the cause and fix it.
Fault 1
topicFan = "SmartVET/" + String(TEAM) + "/line1/fan";Fault 2
// mqtt.loop();Show the explanation (try first!)
- Fault 1: topics are case-sensitive. The ESP32 subscribes to
SmartVET/…, but the commands are sent tosmartvet/…— two different topics. Nothing arrives. - Fault 2: without
mqtt.loop()the library never checks for incoming messages, so the callback is never called. Publishing still works, which makes this bug easy to miss: the machine looks connected but it has gone deaf.
Reflect
- What would happen in a factory if two machines used the same topic?
- Why is a public broker fine for training but not for a real company? Think about security, passwords and a private broker.
- Which data from a real production line would you publish — and how often?
Code
/*
SmartVET – Module 2 – Exercise 2
Connecting the machine: publishing sensor data and receiving commands with MQTT
Board: ESP32 DevKit (Wokwi simulator or real board)
Libraries: "DHT sensor library for ESPx" (DHTesp), "PubSubClient"
License: CC BY-NC-SA 4.0 – SmartVET Erasmus+ project 2025-1-PL01-KA210-VET-000351305
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
// ---- network settings (Wokwi provides a virtual Wi-Fi network) ----
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASS = "";
const char* MQTT_BROKER = "broker.hivemq.com"; // free public broker – never send personal data
const int MQTT_PORT = 1883;
const char* TEAM = "team01"; // every team uses its own ID
// ---- pins (same circuit as Exercise 1) ----
const int DHT_PIN = 15, POT_PIN = 34, LED_ALARM = 2, RELAY_FAN = 5;
DHTesp dht;
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
String topicTemp, topicVib, topicFan;
unsigned long lastPublish = 0;
// Called every time a message arrives on a subscribed topic
void onMessage(char* topic, byte* payload, unsigned int length) {
String msg;
for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
Serial.printf("Command received on %s: %s\n", topic, msg.c_str());
if (msg == "ON") digitalWrite(RELAY_FAN, HIGH);
if (msg == "OFF") digitalWrite(RELAY_FAN, LOW);
}
void connectWiFi() {
WiFi.begin(WIFI_SSID, WIFI_PASS, 6); // channel 6 speeds up the connection in Wokwi
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); }
Serial.println(" connected");
}
void connectMQTT() {
while (!mqtt.connected()) {
String clientId = "smartvet-" + String(TEAM) + "-" + String(random(0xffff), HEX);
Serial.print("Connecting to MQTT broker... ");
if (mqtt.connect(clientId.c_str())) {
Serial.println("connected");
mqtt.subscribe(topicFan.c_str());
} else {
Serial.printf("failed, state=%d – retrying in 2 s\n", mqtt.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
dht.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LED_ALARM, OUTPUT);
pinMode(RELAY_FAN, OUTPUT);
String base = "smartvet/" + String(TEAM) + "/line1/";
topicTemp = base + "temperature";
topicVib = base + "vibration";
topicFan = base + "fan";
connectWiFi();
mqtt.setServer(MQTT_BROKER, MQTT_PORT);
mqtt.setCallback(onMessage);
}
void loop() {
if (!mqtt.connected()) connectMQTT();
mqtt.loop(); // keeps the connection alive and delivers incoming messages
if (millis() - lastPublish >= 5000) { // publish every 5 seconds
lastPublish = millis();
TempAndHumidity data = dht.getTempAndHumidity();
int vibration = map(analogRead(POT_PIN), 0, 4095, 0, 100);
mqtt.publish(topicTemp.c_str(), String(data.temperature, 1).c_str());
mqtt.publish(topicVib.c_str(), String(vibration).c_str());
digitalWrite(LED_ALARM, vibration > 70 ? HIGH : LOW);
Serial.printf("Published: %.1f C, vibration %d %%\n", data.temperature, vibration);
}
}{
"version": 1,
"author": "SmartVET – Bilnet Schools Balıkesir",
"editor": "wokwi",
"parts": [
{"type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {}},
{"type": "wokwi-dht22", "id": "dht1", "top": -96, "left": 196, "attrs": {"temperature": "24", "humidity": "40"}},
{"type": "wokwi-potentiometer", "id": "pot1", "top": 40, "left": -170, "attrs": {}},
{"type": "wokwi-resistor", "id": "r1", "top": 150, "left": 190, "attrs": {"value": "220"}},
{"type": "wokwi-led", "id": "led1", "top": 100, "left": 300, "attrs": {"color": "red"}},
{"type": "wokwi-relay-module", "id": "relay1", "top": 230, "left": 190, "attrs": {}}
],
"connections": [
["esp:TX", "$serialMonitor:RX", "", []],
["esp:RX", "$serialMonitor:TX", "", []],
["dht1:VCC", "esp:3V3", "red", []],
["dht1:SDA", "esp:15", "green", []],
["dht1:GND", "esp:GND.2", "black", []],
["pot1:VCC", "esp:3V3", "red", []],
["pot1:SIG", "esp:34", "blue", []],
["pot1:GND", "esp:GND.1", "black", []],
["esp:2", "r1:1", "orange", []],
["r1:2", "led1:A", "orange", []],
["led1:C", "esp:GND.2", "black", []],
["relay1:VCC", "esp:5V", "red", []],
["relay1:IN", "esp:5", "violet", []],
["relay1:GND", "esp:GND.3", "black", []]
],
"dependencies": {}
}DHT sensor library for ESPx
PubSubClientThis code has not yet been verified in Wokwi or on real hardware. Please report any problems.
Troubleshooting
The Serial Monitor shows “Connecting to Wi-Fi.......” and never finishes.
In Wokwi the network must be “Wokwi-GUEST” with an empty password; the channel 6 in WiFi.begin() only makes the connection faster. On a real board, use your school network’s name and password, remove the “, 6”, and remember that the ESP32 only works with 2.4 GHz Wi-Fi.
“failed, state=-2 – retrying in 2 s” repeats forever.
The ESP32 has Wi-Fi but cannot reach the broker. Check the spelling of broker.hivemq.com and the port 1883. On a real school network, a firewall may block port 1883. The PubSubClient state codes are: -4 timeout, -3 connection lost, -2 connect failed, -1 disconnected, 0 connected, 1 bad protocol, 2 client ID rejected, 3 server unavailable, 4 bad username/password, 5 not authorised.
The ESP32 says “Published” but nothing appears in the browser client.
The topics do not match. Topics are case-sensitive: smartvet/team01/… is not SmartVET/team01/…. Check your TEAM value and subscribe to smartvet/<your team>/# — the # wildcard receives every topic below that level. Also check that the browser client says “connected”.
The fan does not react when I publish a command.
The message must be exactly ON or OFF — upper case, without spaces or quotation marks — on the topic smartvet/<your team>/line1/fan. The ESP32 only receives messages while mqtt.loop() runs in loop(); if that line is missing or the loop is blocked by a long delay(), no command arrives.
I can see data from other teams — or strangers.
broker.hivemq.com is a public broker: anyone who knows a topic can read it and publish to it. That is fine for training, as long as you never send personal or confidential data. Use a unique team ID. Real companies use a private broker with usernames, passwords and encryption (TLS).
Two ESP32s keep disconnecting each other.
A broker allows only one connection per client ID. The program adds a random number to the client ID for exactly this reason — if you replaced it with a fixed name, make it unique again.
Optional real hardware
You do not need any of this — the whole exercise runs in Wokwi. If your school has ESP32 boards, these are the parts for the same circuit.
| Part | Qty | Note |
|---|---|---|
ESP32 DevKit (ESP32-DevKitC V4 or similar)From exercise #1 | 1 | Its GPIO pins use 3.3V logic and are not 5V tolerant. Power the sensors from the 3V3 pin. |
USB cable (data capable; micro-USB or USB-C depending on the board)From exercise #1 | 1 | Charge-only cables carry no data — if the board does not show up on the computer, try another cable first. |
Breadboard (830 tie points)From exercise #1 | 1 | The ESP32 DevKit is wide; use a full-size breadboard so that free rows remain on both sides. |
Jumper wires male-male (at least 15)From exercise #1 | 1 | |
DHT22 (AM2302) temperature & humidity sensorFrom exercise #1 | 1 | Measures the motor temperature in our scenario. Powered from 3V3, its data line is 3.3V too — safe. Wait at least 2 seconds between readings. |
10 kΩ potentiometerFrom exercise #1 | 1 | Stands in for the machine’s vibration level. Outer legs to 3V3 and GND — NOT 5V — middle leg to GPIO 34. |
5 mm red LEDFrom exercise #1 | 1 | The alarm lamp. Long leg (anode) to the resistor, short leg (cathode) to GND. |
220 Ω resistorFrom exercise #1 | 1 | Limits the LED current. At 3.3V it gives about 5–6 mA — bright enough and safe for the pin. |
5V 1-channel relay moduleCautionFrom exercise #1 | 1 | Switches the cooling fan. Connect VCC to the 5V pin. Most 5V relay modules work with the ESP32’s 3.3V signal, but some do not trigger — then use a 3.3V-compatible module or a transistor driver. NEVER switch mains voltage (230V) in class. |
