MQTT for Final-Year IoT Projects: A Practical Student Guide

To send ESP32 sensor data to a dashboard with MQTT, connect the ESP32 to Wi-Fi, connect an MQTT client to a broker, publish readings to topics such as project/lab/temperature, and make the dashboard subscribe to those topics. Use reconnect logic, call the MQTT client loop regularly, avoid long blocking delays, and keep credentials outside your main sketch. For a college demo, a local Mosquitto broker is often easiest to control.

Published by Projectech8 min readPublished
ESP32 development board connected to IoT sensors sending wireless MQTT data through a broker to a laptop dashboard, shown as a clean technical illustration without text overlays.
Illustration generated for this guide.
In this guide

What Is MQTT and Why Is It Useful in an IoT Project?

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for small devices and unreliable networks. Instead of your ESP32 opening a web-style request every time it has data, it keeps one efficient connection open and sends small messages whenever readings change.

For a final-year IoT project, MQTT is useful because:

  • Messages are tiny, so frequent sensor updates cost little bandwidth and battery.
  • Communication is two-way: the device publishes readings and can also receive commands (for example, switching a relay from the dashboard).
  • It decouples the device from the dashboard — the ESP32 does not need to know where the dashboard is, only which broker to talk to.
  • It is widely supported: ESP32 libraries, Python scripts, Node-RED, and many dashboards all speak MQTT.

If your project sends sensor data every few seconds and needs a live dashboard with occasional control, MQTT is usually a better fit than polling an HTTP API. (For the broader picture of cloud options — HTTP, Firebase, Blynk — see How to Connect Your IoT Project to the Cloud: MQTT, HTTP, Firebase and Blynk.)

Understanding the MQTT Broker

Every MQTT system has a broker — a central server that receives messages and routes them to whoever subscribed.

The flow is:

ESP32 (publisher) → broker → dashboard (subscriber)

The ESP32 publishes a message to a topic like project/lab/temperature. The broker holds no project logic; it simply forwards that message to every client currently subscribed to the topic. The dashboard subscribes once and then receives every new reading automatically.

This means the ESP32 and the dashboard never talk to each other directly. Either side can disconnect and reconnect without the other side needing special handling — as long as both know the broker's address.

Key warning: A public test broker is shared with strangers. Never send anything sensitive through one, and never use one for your final assessed demo — use a broker you control.

Topics, Publish and Subscribe

Topics

A topic is a simple text address with levels separated by slashes:

project/lab/temperature
project/lab/humidity
project/lab/pump/command

Design your topics before writing code. A consistent scheme like project/location/sensor keeps things organised when you add more devices later. Avoid spaces and keep names lowercase.

Publish

Publishing means sending a message to a topic. On the ESP32, a typical publish looks like: read the sensor, convert the value to text, and publish it:

float t = readTemperature();
char payload[16];
snprintf(payload, sizeof(payload), "%.1f", t);
client.publish("project/lab/temperature", payload);

Subscribe

Subscribing means asking the broker to forward messages on a topic to you. The ESP32 subscribes to command topics (for example project/lab/pump/command), and the dashboard subscribes to sensor topics. When a message arrives, a callback function handles it.

Which MQTT Broker Should You Use?

Broker option Best for Main advantage Main limitation
Public test broker Classroom experiments No setup needed Shared, no privacy, unreliable
Self-hosted Mosquitto Final-year demos and projects You control access and uptime You must install and run it
Managed cloud broker Remote access beyond the lab Accessible from anywhere Setup and possible usage limits

For learning the protocol, a public test broker is fine for an afternoon. For anything you will demonstrate or be graded on, run your own: Mosquitto on a laptop or a Raspberry Pi on your bench is enough for a college demo, and it keeps your data private.

Eclipse Mosquitto's official documentation covers installation on common platforms: https://mosquitto.org/documentation/

Setting Up an ESP32 with PubSubClient

PubSubClient is the long-standing MQTT library for Arduino-framework ESP32 projects. Install it through the Arduino Library Manager.

Heads-up: The original PubSubClient repository notes that it is no longer actively maintained (as of 2026). It still works for classroom projects, but before you start, check whether an actively maintained fork or an alternative library suits your project better.

A minimal sketch structure:

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

const char* WIFI_SSID = "YourWiFi";
const char* WIFI_PASS = "YourPassword";
const char* MQTT_HOST = "192.168.1.50";
const int   MQTT_PORT = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(500); }
  client.setServer(MQTT_HOST, MQTT_PORT);
  client.setCallback(onMessage);
}

void onMessage(char* topic, byte* payload, unsigned int len) {
  // handle incoming commands here
}

void loop() {
  if (!client.connected()) { reconnect(); }
  client.loop();
  // publish sensor readings on a timer (non-blocking)
}

Key warning: Never hardcode real Wi-Fi passwords or broker credentials in code you upload to GitHub or share. Keep them in a separate secrets file excluded from version control.

Adding Reconnect Logic

Wi-Fi drops. Brokers restart. Your demo network will fail at the worst moment. Without reconnect logic, one dropout kills the whole project.

A simple reconnect function:

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("esp32-client-01")) {
      Serial.println("connected");
      client.subscribe("project/lab/pump/command");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds");
      delay(5000);
    }
  }
}

Call client.loop() on every pass through loop() — it keeps the connection alive and dispatches incoming messages. And never use long delay() calls in your main loop; they starve the MQTT client. Use millis()-based timers for publish intervals instead.

QoS Levels Briefly

MQTT has three Quality of Service levels:

  • QoS 0 — at most once: fire and forget. Fastest, but a message can be lost.
  • QoS 1 — at least once: the broker acknowledges; the message arrives, possibly duplicated.
  • QoS 2 — exactly once: guaranteed single delivery, but slowest and most overhead.

Note: PubSubClient can only publish at QoS 0 (it can subscribe at QoS 0 or 1). So with this library, the QoS 1/2 guidance applies to brokers and to other MQTT libraries that support publishing at those levels. For most student sensor dashboards, QoS 0 is fine anyway — reliable Wi-Fi and reconnect logic matter far more than the QoS number.

Sending Data to a Dashboard

Once the ESP32 publishes to topics, any MQTT-capable dashboard can subscribe and display the data. Common student options:

  • Node-RED on a laptop or Raspberry Pi: drag-and-drop dashboard with gauges and charts, subscribes directly to your topics.
  • A Python script using the Paho MQTT library: subscribes and logs to a file or database.
  • A web dashboard via MQTT over WebSockets, if your broker is configured for it.

The ESP32 side does not change — publish to well-named topics, and let each consumer subscribe to what it needs.

Worked Example: Lab Temperature Monitor

Suppose your project is a lab temperature monitor: a DHT22 sensor on an ESP32 publishes temperature and humidity every 30 seconds, and a Node-RED dashboard on your laptop shows live gauges.

  1. Topics: project/lab/temperature and project/lab/humidity.
  2. Broker: Mosquitto running on your laptop (same machine as Node-RED) — no internet dependency during the demo.
  3. ESP32 firmware: connects to Wi-Fi, connects to the broker with reconnect logic, publishes both readings every 30 seconds using a millis() timer, calls client.loop() continuously.
  4. Dashboard: Node-RED MQTT-in nodes subscribe to both topics and feed gauge widgets.
  5. Testing: unplug the laptop's ethernet / toggle phone hotspot — the ESP32 should reconnect automatically and the dashboard should resume without a restart.

This is a complete, demonstrable MQTT system built from one library, one broker, and one dashboard — each part simple, each part testable.

Common Student Mistakes

Blocking loops with long delays

delay(30000) between publishes starves client.loop() and the connection drops. Use non-blocking millis() timers.

No reconnect logic

The demo works until the Wi-Fi hiccups once. Always implement reconnection for both Wi-Fi and MQTT.

Credentials hardcoded in the sketch

Wi-Fi passwords and broker credentials end up on GitHub. Keep them in a separate, ignored file.

Subscribing before connecting

Calling subscribe() before the connection is established silently does nothing. Subscribe inside the reconnect function after a successful connect.

Using a public broker for the final demo

It works in the lab, then lags or drops during the assessed demo. Use a broker you control.

Confusing topics between publish and subscribe

A typo like project/lab/temprature means the dashboard never receives data. Keep a single list of topic names and copy them exactly.

Final Checklist

Before your demo:

  • Broker choice is deliberate: self-hosted or managed for the final build, not a public test broker.
  • Topic names are consistent, lowercase, and documented.
  • ESP32 connects to Wi-Fi and the broker with automatic reconnect logic.
  • client.loop() is called frequently; no long blocking delays in loop().
  • Publish interval uses a millis() timer.
  • Credentials are outside the main sketch and out of version control.
  • Dashboard subscribes to the correct topics and was tested end to end.
  • You tested a Wi-Fi dropout and watched the system recover by itself.
  • You can explain in your viva: what a broker does, what publish/subscribe means, and why you chose your QoS level.

MQTT rewards a small amount of structure — named topics, reconnect logic, and a broker you control — with a live, robust IoT demo.

Sources:

More project guides

All guides