Summary
MQTT is a lightweight publish-subscribe protocol that lets IoT devices exchange small messages through a central broker. In this guide we explain topics, brokers, QoS levels and retained messages, compare MQTT with HTTP, list free brokers, and build a working ESP32 project that publishes live DHT11 temperature and humidity readings to Mosquitto step by step.
MQTT is a lightweight publish-subscribe protocol; devices publish messages to topics on a broker and other devices subscribe. On an ESP32 we install a library, connect to Wi-Fi and the broker, then publish sensor readings in a few lines of code.
If we have built an IoT project that polls a server every few seconds, we have probably noticed how slow and power-hungry that gets. In this guide we explain how the MQTT protocol works, when it beats HTTP, which free MQTT brokers we can use today, and then we build an ESP32 MQTT project that sends DHT11 temperature and humidity readings to a broker and switches an LED from our laptop.
What is MQTT?
MQTT (Message Queuing Telemetry Transport) is a messaging protocol designed for small devices on unreliable networks. It runs over TCP, keeps one connection open, and wraps each message in a header that can be as small as two bytes.
Every MQTT system has four parts:
-
Publisher: a device that sends a message, such as an ESP32 reading a sensor.
-
Subscriber: a device or app that asks to receive messages, such as a phone dashboard.
-
Broker: the server in the middle. It accepts every message and forwards it to whoever subscribed. Mosquitto, HiveMQ and EMQX are popular brokers.
-
Topic: the address a message is sent to, written like a file path (robocraze/room1/temp).

The publisher never needs to know who is listening. We can add a second dashboard tomorrow without touching the ESP32 code, because the broker handles delivery.
Topics are hierarchical, and subscribers can use two wildcards. A plus sign (+) matches one level, and a hash (#) matches everything below a level.

Components and Supplies
MQTT vs HTTP for IoT
HTTP is built for browsers requesting pages; MQTT is built for devices that send small readings often and need to receive commands quickly. Here is how the two compare for a typical sensor node:
|
Feature |
MQTT |
HTTP |
|
Communication model |
Publish-subscribe through a broker |
Request-response between client and server |
|
Connection |
One persistent TCP connection |
Usually a new request for each exchange |
|
Header size |
As small as 2 bytes |
Often hundreds of bytes of text headers |
|
Receiving commands |
Broker pushes them instantly |
Device must poll the server |
|
One-to-many delivery |
Built in through topics |
Server must send to each client |
|
Delivery guarantees |
QoS 0, 1 and 2 |
None built in; the app retries |
|
Default ports |
1883, or 8883 with TLS |
80, or 443 with TLS |
|
Best for |
Sensor telemetry, remote control, battery devices |
REST APIs, web pages, file uploads |
HTTP still makes sense when a device sends data rarely or talks to a REST API, which is what we do in our ThingSpeak with ESP32 guide. For live, two-way data between many devices, MQTT is the better fit.
Free MQTT brokers to start with
We do not need to run a server to try MQTT. These public brokers accept connections without an account:
|
Broker |
Host |
Port |
Notes |
|
Eclipse Mosquitto test server |
test.mosquitto.org |
1883 (8883 TLS) |
Run by the Mosquitto project; we use it in this tutorial |
|
HiveMQ public broker |
broker.hivemq.com |
1883 |
Has a browser-based client for quick tests |
|
EMQX public broker |
broker.emqx.io |
1883 (8883 TLS) |
Supports MQTT 5.0 |
|
Self-hosted Mosquitto |
PC or Raspberry Pi IP |
1883 |
Private, works on a local network without internet |
Public brokers are shared. Anyone who subscribes to # can read our messages, so we never send passwords or personal data, and we give our topics a unique prefix.
For anything beyond testing, we recommend running our own Mosquitto broker. We install it on a PC or Raspberry Pi, then add these two lines to mosquitto.conf so ESP32 boards on our network can connect (Mosquitto 2.x only listens to the local machine by default):
listener 1883
allow_anonymous true
Then we restart Mosquitto and point the ESP32 sketch below at the computer's IP address instead of test.mosquitto.org. That is all a mosquitto ESP32 setup needs on a home network.
ESP32 MQTT tutorial: wiring a DHT11, code, testing
In this tutorial our ESP32 publishes temperature and humidity every 10 seconds to robocraze/room1/climate and subscribes to robocraze/room1/led so we can switch its onboard LED from a computer.
What we need
|
|
ESP32 38-Pin WiFi + Bluetooth NodeMCU Development Board Dual-core board with built-in Wi-Fi and Bluetooth. This is the board we use in the tutorial. |
|
|
DHT11 Humidity and Temperature Sensor Module 3-pin module with an onboard pull-up resistor that works at 3.3 V, so it connects straight to the ESP32. |
|
|
MB102 830 Points Solderless Breadboard 830 tie points with power rails on both sides, so the ESP32 and sensor fit side by side. |
|
|
7Semi ESP32-S3-Dev-BoardC-1-N8R8 (optional upgrade) ESP32-S3 with 8 MB flash, 8 MB PSRAM and dual USB-C. The same sketch runs on it; change LED_PIN to suit its RGB LED. |
We will also need three jumper wires and a data-capable USB cable. Get the ESP32 MQTT starter parts.
Step 1: Wire the DHT11 to the ESP32
|
DHT11 module pin |
ESP32 pin |
|
VCC (+) |
3V3 |
|
GND (−) |
GND |
|
DATA (S) |
GPIO4 |

Step 2: Install the libraries
-
We add ESP32 support to the Arduino IDE: we open Boards Manager, search for esp32, and install esp32 by Espressif Systems.
-
In Library Manager, we install PubSubClient by Nick O'Leary. This is the MQTT client.
-
We install DHT sensor library by Adafruit and accept the Adafruit Unified Sensor dependency when asked.
If the board has never been online before, we run the sketch from our guide on how to connect ESP32 to Wi-Fi first to confirm our network details.
Step 3: Upload the ESP32 MQTT code
We replace the Wi-Fi name and password, change the robocraze prefix in both topics to something unique, then upload:
#include
#include
#include
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "test.mosquitto.org"; // or your Mosquitto IP
const int MQTT_PORT = 1883;
const char* PUB_TOPIC = "robocraze/room1/climate";
const char* SUB_TOPIC = "robocraze/room1/led";
#define DHTPIN 4
#define DHTTYPE DHT11
#define LED_PIN 2 // onboard LED on most 38-pin ESP32 boards
DHT dht(DHTPIN, DHTTYPE);
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
unsigned long lastSend = 0;
void connectWiFi() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nWi-Fi connected: " + WiFi.localIP().toString());
}
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("Received [%s] %s\n", topic, msg.c_str());
digitalWrite(LED_PIN, msg == "ON" ? HIGH : LOW);
}
void connectMQTT() {
while (!mqtt.connected()) {
String clientId = "esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX);
if (mqtt.connect(clientId.c_str())) {
Serial.println("Connected to broker");
mqtt.subscribe(SUB_TOPIC);
} else {
Serial.printf("Broker refused, rc=%d. Retrying in 5 s\n", mqtt.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
dht.begin();
connectWiFi();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
}
void loop() {
if (!mqtt.connected()) connectMQTT();
mqtt.loop(); // keeps the connection alive
if (millis() - lastSend > 10000) { // every 10 seconds
lastSend = millis();
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(t) || isnan(h)) { Serial.println("DHT11 read failed"); return; }
char payload[48];
snprintf(payload, sizeof(payload), "{\"temp\":%.1f,\"hum\":%.0f}", t, h);
mqtt.publish(PUB_TOPIC, payload, true); // true = retained message
Serial.println("Published " + String(payload));
}
}
The sketch connects to Wi-Fi, connects to the broker with a client ID built from the chip's MAC address (two clients with the same ID keep disconnecting each other), subscribes to the LED topic, and publishes a small JSON message every 10 seconds. The mqtt.loop() call must run often, or the broker drops the connection.
Step 4: Test it
We open the Serial Monitor at 115200 baud and should see "Connected to broker" followed by a published reading every 10 seconds. To watch the messages from a computer, we install the Mosquitto command-line tools and run these two commands in separate terminals:
mosquitto_sub -h test.mosquitto.org -t "robocraze/room1/#" -v
mosquitto_pub -h test.mosquitto.org -t "robocraze/room1/led" -m "ON"
The first command prints each reading as it arrives. The second turns the ESP32's LED on; send OFF to turn it off. For a graphical view, we also like MQTT Explorer and MQTTX.
Troubleshooting: rc=-2 means the ESP32 could not reach the broker, so we check the host name, port and firewall. "DHT11 read failed" almost always means a loose DATA wire or the wrong pin number.
QoS levels and retained messages
MQTT lets each message choose how hard the broker and client work to deliver it. This is the Quality of Service (QoS) level.

|
QoS level |
Guarantee |
When to use it |
|
0 |
At most once; may be lost |
Frequent sensor readings where the next one replaces a missed one |
|
1 |
At least once; may be duplicated |
Alerts and commands that must arrive |
|
2 |
Exactly once |
Billing counts or actions that must not repeat |
PubSubClient publishes at QoS 0 and can subscribe at QoS 0 or 1, which is enough for most hobby projects. When we need QoS 2 or MQTT 5 features, we use Espressif's ESP-MQTT client in ESP-IDF.
A retained message is the last message the broker stores on a topic. Because our sketch publishes with retained set to true, a dashboard that connects later gets the latest reading immediately instead of waiting 10 seconds. A related feature, the Last Will and Testament, tells the broker to publish a message such as "offline" if a device disconnects unexpectedly.
Next step: dashboards and Home Assistant
Once readings reach a broker, any MQTT-aware tool can use them:
-
Node-RED: subscribe with an mqtt-in node and plot readings on its dashboard with a few drag-and-drop nodes.
-
Home Assistant: install the Mosquitto broker add-on, enable the MQTT integration and add the ESP32's topic as a sensor so it appears in automations.
-
Phone apps: MQTT dashboard apps on Android and iOS can subscribe to the same topic and show gauges or buttons.
If we would rather skip broker setup altogether, the Arduino IoT Cloud gives us hosted dashboards for ESP32 boards, and ThingSpeak stores and graphs data over HTTP.







Leave a comment
Please note, comments need to be approved before they are published.