MQTT is the language thousands of sensors, smart plugs and light bulbs use to talk to each other. It’s lightweight, runs on very small boards like the ESP32 and doesn’t depend on any cloud: everything stays inside your network. If you’re into home automation, sooner or later you’ll run into it.
In this guide you’ll see what a broker is, how topics are organized and how to get an ESP32 to publish the temperature of a room.
In short
- MQTT uses the publish/subscribe model: devices don’t talk to each other, they talk to a broker that distributes the messages.
- Every message goes to a topic, a text path such as
casa/salon/temperatura.- The wildcards
+(one level) and#(everything below) let you listen to many topics at once.- QoS decides how strongly delivery is guaranteed, and retain keeps the last value for anyone who connects later.
- In Home Assistant, the most common broker is Mosquitto, which installs as an app.
What MQTT is and why it’s used in home automation
MQTT (Message Queuing Telemetry Transport) is a messaging protocol designed for devices with little memory and unreliable networks. An MQTT message can have a header of just a few bytes, so an ESP32 handles it effortlessly.
In home automation it has three clear advantages:
- It’s local: the broker is in your home, usually on the same machine as Home Assistant.
- It’s universal: Home Assistant, Node-RED, Zigbee2MQTT, Tasmota, ESPHome and almost every programming language understand it.
- It decouples: the sensor doesn’t need to know who reads its data. You can add receivers without touching the sensor.
How it works: broker, publishers and subscribers
Think of the broker as a post office:
- A device publishes a message to a topic: “
casa/salon/temperaturais 22.5”. - The broker receives it and checks who is subscribed to that topic.
- The subscribers (Home Assistant, your phone, another ESP32) get a copy.
The same device can publish and subscribe at the same time. For example, an ESP32 with a relay publishes its state and subscribes to a command topic to turn on or off.
The connection is always opened by the device toward the broker, on port 1883 (unencrypted) or 8883 (with TLS). That’s why a sensor behind any router works without opening ports.

Topics and wildcards: how to organize messages
A topic is a slash-separated path, similar to a folder path. You don’t need to create them beforehand: they exist as soon as someone publishes to them.
A simple structure that’s easy to maintain (in this example, casa means home, salon living room, cocina kitchen and estado state):
casa/salon/temperatura
casa/salon/humedad
casa/cocina/temperatura
casa/cocina/luz/estado
casa/cocina/luz/set
To subscribe to several at once you have two wildcards:
| Wildcard | Means | Example | Receives |
|---|---|---|---|
+ | Any single level | casa/+/temperatura | The temperature of every room |
# | That level and everything below it | casa/# | Everything that happens at home |
Some good practices:
- Lowercase, no spaces or accented characters.
- Don’t start the topic with
/: it creates an empty level that causes confusion. - Keep state (
.../estado) separate from commands (.../set) to avoid loops.

QoS, retained messages and last will
Three options worth understanding from the start:
| Option | What it does | When to use it |
|---|---|---|
| QoS 0 | At most once, no acknowledgment | Frequent sensor readings |
| QoS 1 | At least once; may arrive duplicated | Important commands (turning something on) |
| QoS 2 | Exactly once, with more back-and-forth | Cases where a duplicate would be a problem |
| Retain | The broker stores the last message on the topic | States: whoever connects later gets it right away |
| Last will (LWT) | Message the broker publishes if the device disappears | Knowing whether a sensor is online or offline |
In home automation, the usual setup is QoS 0 or 1 for almost everything, retain on states and a last will on every device.

Setting up the broker in Home Assistant
If you use Home Assistant OS (we explain it in the guide to Home Assistant on a Raspberry Pi):
- Go to Settings, Apps, search for Mosquitto broker and install it.
- Start it and turn on start on boot.
- Create a Home Assistant user just for your MQTT devices (for example,
mqtt-sensores). Mosquitto accepts Home Assistant users. - In Settings, Devices & services, the MQTT integration will show up as discovered. Click Configure.
If you prefer container installs, Mosquitto has an official Docker image. Keep in mind that, since version 2, it only accepts local connections until you configure a listener and authentication.
To see what’s flowing through the broker from a computer with the Mosquitto clients installed:
mosquitto_sub -h 192.168.1.10 -u mqtt-sensores -P 'your-password' -t 'casa/#' -v
-v shows the topic next to each message. It’s the number one debugging tool.
Example: an ESP32 that publishes the temperature
This Arduino IDE sketch uses the PubSubClient library, which you install from the Library Manager. It publishes a reading every minute with retain and announces whether it’s connected using the last will.
#include <WiFi.h>
#include <PubSubClient.h>
const char* WIFI_SSID = "YourWiFi";
const char* WIFI_PASS = "YourWiFiPassword";
const char* MQTT_HOST = "192.168.1.10";
const char* MQTT_USER = "mqtt-sensores";
const char* MQTT_PASS = "your-password";
WiFiClient red;
PubSubClient mqtt(red);
unsigned long ultimaLectura = 0;
float leerTemperatura() {
return 22.5; // replace with your sensor reading
}
void conectarMqtt() {
while (!mqtt.connected()) {
if (mqtt.connect("sensor-salon", MQTT_USER, MQTT_PASS,
"casa/salon/estado", 0, true, "offline")) {
mqtt.publish("casa/salon/estado", "online", true);
} else {
delay(5000);
}
}
}
void setup() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
mqtt.setServer(MQTT_HOST, 1883);
}
void loop() {
if (!mqtt.connected()) conectarMqtt();
mqtt.loop();
if (millis() - ultimaLectura > 60000) {
ultimaLectura = millis();
char texto[8];
snprintf(texto, sizeof(texto), "%.1f", leerTemperatura());
mqtt.publish("casa/salon/temperatura", texto, true);
}
}
For the real reading, pick a sensor with our DHT22 vs DS18B20 comparison. And if the sensor is going to run on batteries, combine MQTT with the deep sleep we explain in powering an ESP32 from a battery.
For Home Assistant to create the entity automatically, the device can publish a configuration message using MQTT discovery (topics starting with homeassistant/). Otherwise, you can declare the sensor manually in the configuration.
MQTT, ESPHome native API or HTTP
| MQTT | ESPHome native API | HTTP | |
|---|---|---|---|
| Needs a broker | Yes | No | No |
| Understood by other systems | Almost all | Mainly Home Assistant | All, but not real time |
| Real time and two-way | Yes | Yes | No (you ask and wait) |
| Effort | Medium | Minimal | Medium |
If you only use Home Assistant and don’t want to write code, ESPHome with its native API is the most convenient option. MQTT shines when several systems need to share the same data or when you write your own firmware.
Frequently asked questions
Does MQTT need internet access? No. The broker can live on your local network and everything works without an outside connection. You only need internet if you use a cloud broker.
Is MQTT secure? It is if you set it up properly: a username and password for each client, no anonymous access and port 1883 not exposed to the internet. For remote access, a WireGuard VPN is better than opening ports.
What’s the difference between MQTT and Zigbee? Zigbee is a radio network between devices; MQTT is a messaging protocol over your IP network. They work together: Zigbee2MQTT translates Zigbee devices into MQTT messages.
Why does my ESP32 keep disconnecting from the broker? The usual causes are mqtt.loop() not being called often enough (because of a long delay), two devices with the same client ID or weak Wi-Fi.
Where do I start if I’ve never used an ESP32? With the basics: our Arduino and ESP32 getting started guide takes you from your first LED to connected projects.



