If you have already built a web server on the ESP32, you have probably started to feel its limits. One board is easy to manage. But what if you have five ESP32 boards in five rooms, and all of them need to send temperature data to one place?
With a web server, your computer has to "visit" every ESP32 one by one and ask for its data. You need to remember every IP address, and when a board dies, you only find out after a request fails. Quite a hassle, right?
This is where MQTT comes in. With this protocol, each ESP32 simply "broadcasts" its data to one central server, and anyone who is interested just listens. It is the protocol behind almost every IoT system, from smart homes to factories.
In this article, we will cover how to use MQTT on the ESP32 from start to finish: understanding the concept, installing the Mosquitto broker, wiring a DHT22 sensor, publishing temperature and humidity data, and controlling an LED with MQTT messages. Let's get started!
What is MQTT?
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for small devices on networks that are not always reliable. It uses a publish/subscribe pattern, unlike HTTP, which uses request/response.
There are three terms you need to know:
- Broker: the central server that receives every message and forwards it to whoever is interested. In this article, the broker is Mosquitto.
- Publisher: a device that sends (publishes) messages, such as an ESP32 sending temperature data.
- Subscriber: a device or application that subscribes to receive messages, such as a laptop or a dashboard.
Every message is sent to a topic, a text "address" separated by slashes, for example home/living-room/temperature. Publishers and subscribers do not need to know each other. They only need to know the broker and agree on the topic names.
Illustration of the MQTT flow: the ESP32 sends data to the broker, and the broker forwards it to every subscribed device.
Think of the broker as a radio station with many channels. The ESP32 talks on the home/living-room/temperature channel, and anyone tuned in to that channel hears it. A single device can be a publisher and a subscriber at the same time, and that is exactly what we are going to build.
Why Use MQTT on the ESP32?
Here are a few reasons why MQTT is the go-to choice for IoT projects:
- Lightweight: messages are tiny, which suits microcontrollers and slow connections.
- Easy to add devices: a new ESP32 only needs the broker's address. There are no other device IP addresses to remember.
- Two-way communication: the ESP32 can send sensor data and receive commands over the same connection.
- Built-in offline detection: with Last Will and Testament, the broker can announce that a device has dropped off.
- Supported by many applications: Home Assistant, Node-RED, Grafana (through Telegraf), and many other IoT dashboards can read MQTT data.
To keep things balanced, here are the downsides:
- It needs a broker that is always on. If the broker goes down, all communication stops.
- You cannot open it directly in a browser like a web page. You need an MQTT client application or a dashboard.
- No encryption by default. The standard port
1883sends data, including passwords, unencrypted.
For comparison, here is how it stacks up against the web server approach from the previous article:
| Aspect | Web Server (HTTP) | MQTT |
|---|---|---|
| Communication pattern | Request/response | Publish/subscribe |
| Who starts | The browser asks, the ESP32 answers | The ESP32 sends whenever it wants |
| Extra server | ❌ Not needed | ✅ Needs a broker |
| Many devices | ⚠️ Must know every board's IP | ✅ Only the broker's address |
| Best for | Simple control from a browser | Periodic sensor data and automation |
Preparation
This article is a follow-up to how to program the ESP32 with Arduino IDE. If your Arduino IDE does not know about ESP32 boards yet, please follow that article first.
Here is what you need:
- An ESP32 DevKit V1 (30 or 38 pins) and a micro USB cable that supports data.
- A DHT22 sensor (AM2302), a 10kΩ resistor, a breadboard, and 3 female-to-male jumper wires. If your sensor is a three-pin module, you do not need the resistor because one is usually already mounted on the module.
- Arduino IDE 2.3.x with the esp32 by Espressif Systems package, version 3.3.x.
- A computer for the broker: a Raspberry Pi, a mini PC, or a laptop running Ubuntu 24.04 LTS / 26.04 LTS or Raspberry Pi OS, connected to the same network as the ESP32.
- A 2.4 GHz WiFi network. The classic ESP32 does not support 5 GHz WiFi.
Illustration of the required components: ESP32 DevKit V1, DHT22 sensor, 10kΩ resistor, breadboard, jumper wires, and a micro USB cable.
The commands and code in this article are intended for Mosquitto 2.x (version 2.0.18 in the Ubuntu 24.04 repository and 2.0.22 in Ubuntu 26.04), the ArduinoMqttClient 0.1.8 library, and DHT sensor library 1.4.7.
A note on the core version: at the time of writing, Espressif has just released version 4.0.0 of the esp32 package (November 19, 2026), based on ESP-IDF v6. Since a major release like this usually takes a while before every third-party library catches up, the code in this article targets the 3.3.x series. If you are already on 4.0.0 and run into compile errors, downgrade through the Boards Manager.
Voltage warning: ESP32 GPIO pins operate at 3.3V and are not 5V tolerant. That is why the DHT22 in this project is powered from the 3V3 pin, not from VIN/5V. If the sensor is powered from 5V, its data signal is also 5V and can damage the ESP32 pin.
In the examples below, the broker computer uses the IP address 192.168.1.10. Replace it with the IP address on your own network.
How to Install the Mosquitto Broker
Eclipse Mosquitto is the most popular open source MQTT broker. It is small and runs smoothly even on a Raspberry Pi. If you do not have a Raspberry Pi ready to go yet, follow how to install Raspberry Pi headless first.
Step #1: Install Mosquitto
Log in to the computer that will act as the broker, then update the package list and install Mosquitto together with its client programs:
sudo apt update
sudo apt install mosquitto mosquitto-clients -yThe mosquitto package is the broker itself, while mosquitto-clients provides the mosquitto_pub and mosquitto_sub commands we will use for testing. Once installed, check whether the service is running:
systemctl is-active mosquittoIf the output is active, the broker is up.
Step #2: Create a User and Password
Since Mosquitto 2.0, two important changes have broken many older tutorials:
- Without extra configuration, the broker only accepts connections from the computer itself (
127.0.0.1). Your ESP32 will be rejected. - Once a listener is opened to the network, connections without a login are no longer allowed by default.
So we need to create a user first. Create a password file containing a user named esp32 with the following command, then type the password you want twice:
sudo mosquitto_passwd -c /etc/mosquitto/passwd esp32Be careful with the
-coption: it creates a new file and overwrites an existing one. To add more users later, run the same command without-c, for examplesudo mosquitto_passwd /etc/mosquitto/passwd laptop.
Next, make sure the password file can be read by the mosquitto user that runs the broker, and not by anyone else:
sudo chown mosquitto:mosquitto /etc/mosquitto/passwd
sudo chmod 600 /etc/mosquitto/passwdStep #3: Open a Listener for the Local Network
On Ubuntu and Raspberry Pi OS, extra configuration goes into the /etc/mosquitto/conf.d/ folder. Create a new file with the following command:
sudo nano /etc/mosquitto/conf.d/lokal.confAdd the following configuration:
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwdSave the file by pressing CTRL+X, then Y, and Enter. A quick explanation of each line:
- listener 1883: the broker accepts connections on port 1883 from all network interfaces, not just from the computer itself.
- allow_anonymous false: connections without a username and password are rejected.
- password_file: the location of the password file created in the previous step.
Restart Mosquitto so the new configuration is loaded:
sudo systemctl restart mosquittoThen check whether the broker is listening on port 1883:
sudo ss -tlnp | grep 1883The output looks roughly like this:
LISTEN 0 100 0.0.0.0:1883 0.0.0.0:* users:(("mosquitto",pid=1234,fd=5))
LISTEN 0 100 [::]:1883 [::]:* users:(("mosquitto",pid=1234,fd=6))If the address shown is 0.0.0.0:1883 (not 127.0.0.1:1883), the broker can now be reached from other devices on the network. If the service fails to start, find out why with sudo journalctl -u mosquitto -n 20.
Using the UFW firewall? If UFW is active on the broker computer, as in the guide on how to secure a Linux VPS, allow port 1883 only from the local network, for example
sudo ufw allow from 192.168.1.0/24 to any port 1883 proto tcp. Adjust192.168.1.0/24to match your network.
Step #4: Test the Broker from the Terminal
Before bringing in the ESP32, make sure the broker works. Open a first terminal on the broker computer and subscribe to every topic under home/ (replace YourMqttPassword with the password you just created):
mosquitto_sub -h localhost -u esp32 -P 'YourMqttPassword' -t 'home/#' -vThis command will sit "silently" waiting for messages. Leave it running, then open a second terminal and send a message:
mosquitto_pub -h localhost -u esp32 -P 'YourMqttPassword' -t 'home/test' -m 'hello MQTT'The first terminal will show output like this:
home/test hello MQTTIf the message shows up, congratulations! Your broker is working. The # in the topic is a wildcard meaning "every topic below this level". There is also the + wildcard, which stands for exactly one level, for example home/+/temperature for the temperature in every room.
Finally, note down the broker computer's IP address with the following command, because it goes into the ESP32 program:
hostname -IHow to Send Sensor Data from the ESP32 over MQTT
Step #1: Wire the DHT22 Sensor to the ESP32
Hold the DHT22 sensor with the grid side facing you and the legs pointing down. From left to right, the legs are pin 1 (VCC), pin 2 (DATA), pin 3 (not used), and pin 4 (GND).
Unplug the ESP32's USB cable before wiring, then connect the components according to the following connection table:
| From | To |
|---|---|
| DHT22 pin 1 (VCC) | ESP32 3V3 pin |
| DHT22 pin 2 (DATA) | ESP32 D4 pin (GPIO 4) |
| 10kΩ resistor | Between DHT22 pin 1 (VCC) and pin 2 (DATA) |
| DHT22 pin 3 | Not connected |
| DHT22 pin 4 (GND) | ESP32 GND pin |
Illustration of the DHT22 circuit on a breadboard. Follow the connection table above.
The 10kΩ resistor acts as a pull-up that keeps the data line stable. On the module version of the DHT22 (three pins labeled +, out, and -), simply connect + to 3V3, out to D4, and - to GND. If you want to get to know this sensor better, read how to read a DHT22 sensor with Raspberry Pi.
Step #2: Install the Required Libraries
Open Arduino IDE, then open the Library Manager through Sketch → Include Library → Manage Libraries… (Ctrl+Shift+I). Search for and install these two libraries:
- ArduinoMqttClient by Arduino, the MQTT client library.
- DHT sensor library by Adafruit, the DHT sensor reader. When asked about dependencies, choose Install All so that Adafruit Unified Sensor is installed as well.
Why not PubSubClient? Almost every ESP32 MQTT tutorial uses the PubSubClient library. However, at the time of writing, the official PubSubClient README carries a warning that the library is no longer maintained, and its author recommends picking another library that is actively maintained. That is why this article uses ArduinoMqttClient, the official library from the Arduino team. Keep in mind that this library is still labeled beta (version 0.1.x), although it already supports the ESP32 and publishing with QoS 0, 1, and 2.
Step #3: Write the ESP32 MQTT Program
Create a new sketch through File → New Sketch, then replace its entire contents with the code below. Adjust the WiFi name and password, the broker's IP address, and the MQTT password at the top:
#include <WiFi.h>
#include <ArduinoMqttClient.h>
#include <DHT.h>
// ---- WiFi settings ----
const char* WIFI_SSID = "YourWiFiName";
const char* WIFI_PASS = "YourWiFiPassword";
// ---- MQTT broker settings ----
const char* MQTT_HOST = "192.168.1.10"; // IP address of the broker computer
const int MQTT_PORT = 1883;
const char* MQTT_USER = "esp32";
const char* MQTT_PASS = "YourMqttPassword";
const char* CLIENT_ID = "esp32-living-room"; // must be unique for every device
// ---- Topics ----
const char* TOPIC_TEMP = "home/living-room/temperature";
const char* TOPIC_HUMIDITY = "home/living-room/humidity";
const char* TOPIC_STATUS = "home/living-room/status";
const char* TOPIC_LED = "home/living-room/led";
const int DHT_PIN = 4; // GPIO connected to the DHT22 DATA pin
const int LED_PIN = 2; // built-in blue LED on the DevKit V1 board
const unsigned long SEND_INTERVAL = 10000; // send data every 10 seconds
const unsigned long RETRY_INTERVAL = 5000; // pause between connection attempts
DHT dht(DHT_PIN, DHT22);
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
unsigned long lastSend = 0;
unsigned long lastRetry = 0;
// Send one text message to a topic
void sendMessage(const char* topic, const String& payload, bool retain) {
mqttClient.beginMessage(topic, (unsigned long)payload.length(), retain);
mqttClient.print(payload);
mqttClient.endMessage();
}
// Called automatically whenever a message arrives on a subscribed topic
void onMqttMessage(int messageSize) {
String topic = mqttClient.messageTopic();
String payload = "";
while (mqttClient.available()) {
payload += (char)mqttClient.read();
}
Serial.print("Message received [");
Serial.print(topic);
Serial.print("]: ");
Serial.println(payload);
if (topic == TOPIC_LED) {
if (payload == "on") {
digitalWrite(LED_PIN, HIGH);
} else if (payload == "off") {
digitalWrite(LED_PIN, LOW);
}
}
}
// Connect to the broker, announce the status, then subscribe
bool connectMqtt() {
Serial.print("Connecting to the MQTT broker... ");
// "Last will": the message the broker sends if the ESP32 drops off suddenly
String will = "offline";
mqttClient.beginWill(TOPIC_STATUS, will.length(), true, 1);
mqttClient.print(will);
mqttClient.endWill();
if (!mqttClient.connect(MQTT_HOST, MQTT_PORT)) {
Serial.print("failed, error code = ");
Serial.println(mqttClient.connectError());
return false;
}
Serial.println("connected!");
sendMessage(TOPIC_STATUS, "online", true); // retain: the status is always stored
mqttClient.subscribe(TOPIC_LED); // listen for LED commands
return true;
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
dht.begin();
// connect to WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
// MQTT client identity and settings
mqttClient.setId(CLIENT_ID);
mqttClient.setUsernamePassword(MQTT_USER, MQTT_PASS);
mqttClient.setKeepAliveInterval(15 * 1000L); // "still alive" signal every 15 seconds
mqttClient.setConnectionTimeout(5 * 1000L); // how long to wait for the broker's reply
mqttClient.onMessage(onMqttMessage);
connectMqtt();
}
void loop() {
// WiFi down? Wait, the ESP32 will try to reconnect on its own
if (WiFi.status() != WL_CONNECTED) {
delay(500);
return;
}
// Broker connection lost? Retry every 5 seconds
if (!mqttClient.connected()) {
if (millis() - lastRetry >= RETRY_INTERVAL) {
lastRetry = millis();
connectMqtt();
}
return;
}
mqttClient.poll(); // receive incoming messages and keep the connection alive
if (millis() - lastSend >= SEND_INTERVAL) {
lastSend = millis();
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // in degrees Celsius
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read the DHT22 sensor, will try again later");
return;
}
sendMessage(TOPIC_TEMP, String(temperature, 1), false);
sendMessage(TOPIC_HUMIDITY, String(humidity, 1), false);
Serial.printf("Sent: temperature %.1f C, humidity %.1f %%\n", temperature, humidity);
}
}The code is fairly long, but the pattern is simple. We will break it down in the Understanding How the Code Works section once the program is running.
Step #4: Upload and Watch the Data Come In
Plug the ESP32 back into your computer, make sure the ESP32 Dev Module board and the correct port are selected in the Tools menu, then click the Upload button. If the upload gets stuck at Connecting...., press and hold the BOOT button on the board until the upload percentage starts moving.
When it is done, open Tools → Serial Monitor (Ctrl+Shift+M) at 115200 baud. The output looks roughly like this:
Connecting to WiFi....
Connected! IP address: 192.168.1.37
Connecting to the MQTT broker... connected!
Sent: temperature 28.4 C, humidity 71.2 %
Sent: temperature 28.4 C, humidity 71.3 %Now go back to the terminal on the broker computer that is still running mosquitto_sub from the earlier test. The data from the ESP32 will appear roughly like this:
home/living-room/status online
home/living-room/temperature 28.4
home/living-room/humidity 71.2
home/living-room/temperature 28.4
home/living-room/humidity 71.3Pretty cool, right? Your sensor data now flows across the network every 10 seconds, and any application connected to the broker can read it too.
Step #5: Control the LED with MQTT Messages
MQTT works in both directions. Our program subscribes to the home/living-room/led topic, so the ESP32 can receive commands. From the second terminal on the broker computer, send the message on:
mosquitto_pub -h localhost -u esp32 -P 'YourMqttPassword' -t 'home/living-room/led' -m 'on'The blue LED on the ESP32 board will light up, and the Serial Monitor shows Message received [home/living-room/led]: on. Send off with the same command to turn it off again.
Now try one more thing: unplug the ESP32's USB cable and watch the mosquitto_sub terminal. Within about half a minute, the following line will appear:
home/living-room/status offlineYet the ESP32 is already off and could not possibly send anything. This message is sent by the broker on behalf of the ESP32, and that is the Last Will and Testament feature we will discuss below.
Understanding How the Code Works
Now, let's look at what is really going on inside that program.
Connecting to the Broker
The MqttClient object needs a WiFiClient as its communication channel. In setup(), we set the client identity with setId() and the login details with setUsernamePassword(), then connect through mqttClient.connect(MQTT_HOST, MQTT_PORT).
The client ID must be unique. If two devices use the same client ID, the broker disconnects the one that connected first, and the two will keep "kicking" each other off forever. So give every ESP32 a different name.
Sending Messages (Publish)
Sending a message with the ArduinoMqttClient library always takes three steps, which we wrap in the sendMessage() function:
mqttClient.beginMessage(topic, (unsigned long)payload.length(), retain);
mqttClient.print(payload);
mqttClient.endMessage();beginMessage() opens a message for a topic, print() fills in its contents, and endMessage() sends it. Sensor values are sent as plain text, such as 28.4, so any application can read them easily.
Receiving Messages (Subscribe)
Receiving messages takes two things: registering a handler function with mqttClient.onMessage(onMqttMessage), then subscribing with mqttClient.subscribe(TOPIC_LED). Every time a message arrives, onMqttMessage() is called, and the payload is read character by character with mqttClient.read().
Notice that subscribe() is called inside connectMqtt(), not in setup(). By default, this library uses a clean session, so the broker forgets subscriptions every time the connection drops. Placing it there means the subscription is registered again automatically after the ESP32 reconnects.
Retained Messages and Last Will
The retain parameter makes the broker store the last message on a topic. A subscriber that has just connected receives that message right away without waiting for the next one. We use it for the status topic, so anyone who subscribes immediately knows whether the ESP32 is online or offline.
Last Will and Testament (LWT) is a "will" the ESP32 leaves with the broker when it first connects, through beginWill() and endWill(). It says: "if I disappear without saying goodbye, please send offline to the status topic". The broker knows a client has disappeared from the keep-alive signal. According to the MQTT specification, if nothing is heard for one and a half times the keep-alive interval, the client is considered disconnected. With the 15-second interval in our program, the will is sent about 20–30 seconds after the ESP32 goes off.
Keeping the Connection Alive in loop()
The mqttClient.poll() function is the heart of this program. Every time it is called, it checks for incoming messages and sends the keep-alive signal to the broker. For that reason, do not put long delay() calls inside loop(). Periodic sending is done by checking the time with millis(), just like in the web server article.
The beginning of loop() also handles disconnections: if WiFi is gone, the program waits, and if the broker connection is gone, the program retries every 5 seconds. This way, the ESP32 recovers on its own after the router or the broker is restarted.
Tips for Using MQTT on the ESP32
Tip #1: Design Your Topic Names Carefully
Use a consistent hierarchical pattern, such as location/room/data-type. Use lowercase letters, avoid spaces, and do not start a topic with a slash. With a tidy pattern, wildcards become very handy: home/+/temperature picks up the temperature in every room, and home/kitchen/# picks up everything from the kitchen.
Tip #2: Send Data as JSON
As your data grows, you can combine it into a single JSON message, such as {"temperature":28.4,"humidity":71.2}. Dashboards like Home Assistant and Node-RED can parse this format directly. Keep in mind that the ArduinoMqttClient library limits the message payload to 256 bytes by default on the ESP32. For larger messages, raise the limit with mqttClient.setTxPayloadSize() before connecting to the broker.
Tip #3: Do Not Expose Port 1883 to the Internet
Port 1883 is unencrypted, so the username, password, and all data are sent as is. Inside a home network, the risk is small. However, do not set up port forwarding for this port from your router to the internet. If the broker has to be reachable from outside, use MQTT over TLS (port 8883) or connect through a VPN.
Tip #4: Adjust the Sending Interval
According to the official Adafruit library example, the DHT22 is a slow sensor and should be given a few seconds between readings. For room temperature that changes slowly, an interval of 30–60 seconds is usually enough, and it is easier on both the network and storage.
Troubleshooting Common Problems
When the broker connection fails, the program prints the error code from connectError(). Here is what the most common codes mean, as defined in the library's source code:
| Code | Meaning | Solution |
|---|---|---|
-2 |
Connection refused at the network level | Check the broker's IP address, make sure Mosquitto is running and the listener is open (Step #3), check the firewall |
-1 |
The broker did not answer in time | Check the network and make sure the target port really is the MQTT port |
2 |
Client ID rejected | Change the CLIENT_ID value |
4 |
Wrong username or password | Check MQTT_USER and MQTT_PASS, or reset the password with mosquitto_passwd |
5 |
Not authorized | Make sure the user exists in the password file and password_file is correct |
Other problems you may run into:
| Problem | Possible Cause | Solution |
|---|---|---|
mosquitto_sub works on the broker computer, but the ESP32 always fails |
The broker is still in local-only mode (127.0.0.1) |
Create the lokal.conf file containing listener 1883, then restart Mosquitto |
| Mosquitto fails to start after a configuration change | A typo in the configuration file or an unreadable password file | Check sudo journalctl -u mosquitto -n 20, then check the password file's owner and permissions |
Failed to read the DHT22 sensor keeps appearing |
Wrong wiring, missing pull-up resistor, or wrong pin | Compare with the connection table and make sure DHT_PIN matches |
| The MQTT connection keeps dropping and reconnecting | Two devices share the same client ID | Give each device a different CLIENT_ID |
| The connection often drops for no clear reason | A long delay() means poll() is rarely called |
Replace delay() with a millis() check |
| The Serial Monitor keeps printing dots | Wrong WiFi SSID/password, or the WiFi is 5 GHz only | Check the SSID and password, and make sure the 2.4 GHz network is enabled |
Conclusion
From this article, we can conclude that MQTT is a tidy way to connect many IoT devices. The ESP32 does not need to know who will read its data. It simply sends messages to a topic on the broker, and the broker forwards them to everyone who has subscribed.
With the Mosquitto broker, the ArduinoMqttClient library, and a DHT22 sensor, you now have the foundation of a temperature and humidity monitoring system that can grow to many rooms. Adding a new device is just a matter of changing the client ID and the topic names.
Things to Remember
- Since Mosquitto 2.0, the broker only accepts local connections until you add a
listener, and connections without a login are rejected by default. - Every device must have a unique client ID.
- Call
mqttClient.poll()as often as possible and avoid longdelay()calls inloop(). - Subscribe again every time the ESP32 reconnects to the broker.
- Power the DHT22 from the 3V3 pin, because ESP32 GPIO pins are not 5V tolerant.
- Port 1883 is unencrypted, so do not expose it to the internet.
Next Steps
From here, you can add a second ESP32 in another room, show the data on a dashboard such as Node-RED or Home Assistant, or store the data in a database so you can chart it. If your broker runs on a Raspberry Pi, the same device can also run Pi-hole as an ad blocker for your home network.
Resources and Useful Links
- Eclipse Mosquitto documentation: migrating to 2.0
- Eclipse Mosquitto documentation: authentication methods
- ArduinoMqttClient library repository
- Adafruit DHT sensor library repository
- PubSubClient repository (see the warning in the README)
- arduino-esp32 release notes
Have a question or ran into trouble while following this tutorial? Feel free to ask, and stay tuned to Teknotut for the next ESP32 project!
I hope this article helps.



