IoT and Edge AI

How to Use MQTT on the ESP32: A Practical Tutorial

Step-by-step ESP32 MQTT tutorial: set up Mosquitto, publish and subscribe with PubSubClient, add last will, authentication and TLS, or use ESP-IDF's esp-mqtt.

On this page
  1. What you’ll build
  2. MQTT in five minutes
  3. What you need
  4. Step 1: Set up a Mosquitto broker
  5. Step 2: Install the ESP32 board package and PubSubClient
  6. Step 3: The complete sketch
  7. Step 4: Test from your computer
  8. How the code works
  9. Designing your topics
  10. Making it production-ready
  11. The ESP-IDF alternative
  12. Troubleshooting
  13. FAQ

What you’ll build

By the end of this tutorial you’ll have an ESP32 that:

  • Connects to Wi-Fi and to an MQTT broker running on your own computer or server
  • Publishes a small JSON telemetry message every 10 seconds
  • Subscribes to a command topic and switches an LED on or off
  • Reports whether it’s online or offline using MQTT’s retained messages and last will feature
  • Reconnects automatically if Wi-Fi or the broker drops, without freezing the rest of the program

We’ll use the Arduino framework and the widely used PubSubClient library, then show how to add authentication and TLS, and finish with the equivalent code for Espressif’s own ESP-IDF framework.

MQTT in five minutes

MQTT is a lightweight publish/subscribe messaging protocol that’s very common in IoT. The key ideas:

  • Broker: a server that receives all messages and passes them to whoever is interested. Mosquitto, EMQX and HiveMQ are well-known brokers. Cloud IoT services also provide MQTT endpoints.
  • Clients: devices and apps that connect to the broker. Your ESP32 is a client, and so is the command-line tool you’ll use for testing.
  • Topics: hierarchical strings like home/esp32-demo/telemetry. Clients publish messages to topics and subscribe to topics they care about. Publishers and subscribers never talk to each other directly.
  • Wildcards: subscribers can use + for one level (home/+/telemetry) and # for everything below (home/esp32-demo/#).
  • QoS (Quality of Service): 0 = at most once (fire and forget), 1 = at least once (may be duplicated), 2 = exactly once (more overhead).
  • Retained messages: the broker keeps the last retained message on a topic and sends it to any new subscriber immediately. That’s useful for state like “online” or “LED is ON.”
  • Last will and testament (LWT): a message the client registers when connecting. If the client disappears without disconnecting cleanly, the broker publishes it for the client.
  • Keep-alive: clients ping the broker periodically so both sides can detect dead connections.

The standard unencrypted MQTT port is 1883, and MQTT over TLS conventionally uses 8883.

What you need

  • An ESP32 development board (any common variant with Wi-Fi works)
  • A USB cable and a computer
  • The Arduino IDE (or PlatformIO) with the ESP32 board package
  • The Mosquitto broker and its command-line clients, installed on your computer, a Raspberry Pi or a server on the same network
  • Optionally, an LED and resistor (many boards have an onboard LED you can use instead)

Step 1: Set up a Mosquitto broker

Install Mosquitto using your system’s package manager (for example sudo apt install mosquitto mosquitto-clients on Debian-based Linux). Installers are also available for Windows and macOS.

One important detail: Mosquitto 2.0 and later, by default, only accept connections from the same machine unless you configure a listener. Many tutorials were written for older versions, so this is a frequent source of “connection refused” errors.

For a quick local test on a trusted home network, add a config file (on Linux, often /etc/mosquitto/conf.d/local.conf):

listener 1883
allow_anonymous true

Then restart Mosquitto. Only use anonymous access for testing on a private network. We’ll add a username and password later.

Note the IP address of the machine running the broker. You’ll need it in the sketch.

You can also use a public test broker such as test.mosquitto.org to get started. Anyone can read what you publish there, though, so never send real data or credentials to one.

Step 2: Install the ESP32 board package and PubSubClient

  1. In the Arduino IDE, add the ESP32 board package from Espressif via the Boards Manager (Espressif’s documentation gives the current board manager URL).
  2. Select your board and its serial port.
  3. Open the Library Manager and install PubSubClient by Nick O’Leary.

Step 3: The complete sketch

Replace the Wi-Fi details, broker address and LED pin with your own values. GPIO 2 drives the onboard LED on many ESP32 DevKit boards, but check your board’s pinout.

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

// ---- Settings ----
const char* WIFI_SSID = "your-ssid";
const char* WIFI_PASS = "your-wifi-password";
const char* MQTT_HOST = "192.168.1.10";   // IP of your Mosquitto broker
const uint16_t MQTT_PORT = 1883;
const int LED_PIN = 2;                     // check your board's pinout

const char* TOPIC_STATUS    = "home/esp32-demo/status";
const char* TOPIC_TELEMETRY = "home/esp32-demo/telemetry";
const char* TOPIC_LED_SET   = "home/esp32-demo/led/set";
const char* TOPIC_LED_STATE = "home/esp32-demo/led/state";

WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
String clientId;

unsigned long lastReconnectAttempt = 0;
unsigned long lastTelemetry = 0;

void onMessage(char* topic, byte* payload, unsigned int length) {
  String message;
  for (unsigned int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  Serial.printf("Message on %s: %s\n", topic, message.c_str());

  if (strcmp(topic, TOPIC_LED_SET) == 0) {
    bool on = message.equalsIgnoreCase("ON");
    digitalWrite(LED_PIN, on ? HIGH : LOW);
    mqtt.publish(TOPIC_LED_STATE, on ? "ON" : "OFF", true);  // retained
  }
}

void connectWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.printf("\nConnected, IP address: %s\n", WiFi.localIP().toString().c_str());
}

bool connectMqtt() {
  // Register a last will: if we vanish, the broker publishes "offline" (retained)
  bool ok = mqtt.connect(clientId.c_str(),
                         nullptr, nullptr,              // username, password
                         TOPIC_STATUS, 1, true, "offline");
  if (ok) {
    mqtt.publish(TOPIC_STATUS, "online", true);
    mqtt.subscribe(TOPIC_LED_SET);
    Serial.println("MQTT connected");
  } else {
    Serial.printf("MQTT connect failed, state=%d\n", mqtt.state());
  }
  return ok;
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);

  // A unique client ID per device; brokers disconnect duplicates
  clientId = "esp32-demo-" + String((uint32_t)ESP.getEfuseMac(), HEX);

  connectWiFi();
  mqtt.setServer(MQTT_HOST, MQTT_PORT);
  mqtt.setCallback(onMessage);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    connectWiFi();
  }

  if (!mqtt.connected()) {
    // Retry every 5 seconds without blocking the rest of the loop
    unsigned long now = millis();
    if (now - lastReconnectAttempt > 5000) {
      lastReconnectAttempt = now;
      connectMqtt();
    }
  } else {
    mqtt.loop();  // processes incoming messages and keep-alive pings
  }

  unsigned long now = millis();
  if (mqtt.connected() && now - lastTelemetry > 10000) {
    lastTelemetry = now;
    char payload[96];
    snprintf(payload, sizeof(payload),
             "{\"uptime_s\":%lu,\"rssi\":%d}",
             now / 1000, WiFi.RSSI());
    mqtt.publish(TOPIC_TELEMETRY, payload);
  }
}

Upload the sketch and open the Serial Monitor at 115200 baud. You should see the Wi-Fi connection, then “MQTT connected.”

Step 4: Test from your computer

In one terminal, subscribe to everything the device publishes:

mosquitto_sub -h 192.168.1.10 -t "home/esp32-demo/#" -v

You should see home/esp32-demo/status online, then a telemetry message every 10 seconds.

In a second terminal, switch the LED:

mosquitto_pub -h 192.168.1.10 -t "home/esp32-demo/led/set" -m "ON"
mosquitto_pub -h 192.168.1.10 -t "home/esp32-demo/led/set" -m "OFF"

Now unplug the ESP32. After the keep-alive period runs out, the broker publishes the last will and the subscriber shows home/esp32-demo/status offline. Because the status message is retained, any dashboard that connects later still sees the correct state.

How the code works

  • clientId is built from the chip’s MAC address, so each board has a unique ID. If two clients connect with the same ID, the broker disconnects the older one, which causes confusing connect/disconnect loops.
  • mqtt.connect(...) registers the last will on the status topic with QoS 1 and the retain flag set.
  • Retained “online” message: published right after connecting, it overwrites the retained “offline” from any previous disconnect.
  • Subscriptions go inside connectMqtt(), because a fresh connection with a clean session forgets earlier subscriptions. Subscribing on every reconnect avoids silently losing commands.
  • Non-blocking reconnect: instead of looping until the broker answers, the sketch tries every five seconds and lets the rest of loop() keep running. Your device can still read sensors or handle buttons while offline.
  • mqtt.loop() must run frequently. It receives incoming messages and sends keep-alive pings. Long delay() calls elsewhere in your code can cause disconnects.
  • Telemetry is a small JSON string built with snprintf. Most dashboards and automation tools (Home Assistant, Node-RED, Grafana via a bridge) parse JSON easily.

Designing your topics

A little planning makes your system much easier to extend:

  • Use a consistent hierarchy, such as <site>/<device-id>/<category>/<item>. For example: home/esp32-demo/telemetry or home/esp32-demo/led/set.
  • Separate commands from state. Publish commands to .../set and have the device confirm the real state on .../state. This avoids feedback loops and tells you whether the command actually worked.
  • Retain state, not events. Retain “LED is ON” or “online.” Don’t retain one-off events like “button pressed,” or every new subscriber will receive an old event.
  • Avoid leading slashes and spaces in topic names, and keep them reasonably short.
  • Include the device ID so many devices can share a broker.

Making it production-ready

Add authentication

Create a password file for Mosquitto:

sudo mosquitto_passwd -c /etc/mosquitto/passwd esp32demo

Then update the config:

listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd

In the sketch, pass the username and password to connect() instead of nullptr. On a shared or exposed network, also use Mosquitto’s access control lists (ACLs) so each device can only publish and subscribe to its own topics.

Add TLS

Without TLS, passwords and data cross the network in plain text. To encrypt the connection:

  1. Configure Mosquitto with a certificate and a listener on port 8883.
  2. In the sketch, swap WiFiClient for WiFiClientSecure and give it the certificate authority (CA) certificate that signed the broker’s certificate:
#include <WiFiClientSecure.h>

const char* CA_CERT = R"EOF(
-----BEGIN CERTIFICATE-----
...your CA certificate here...
-----END CERTIFICATE-----
)EOF";

WiFiClientSecure secureClient;
PubSubClient mqtt(secureClient);

// in setup():
secureClient.setCACert(CA_CERT);
mqtt.setServer(MQTT_HOST, 8883);

When you connect by hostname, make sure the name matches the certificate. Avoid setInsecure() outside quick experiments, because it skips server verification and leaves the connection open to impersonation. Cloud IoT services such as AWS IoT Core typically also require client certificates (mutual TLS), which WiFiClientSecure supports through setCertificate() and setPrivateKey().

Other robustness tips

  • Message size: PubSubClient’s default packet buffer is small (256 bytes, including the topic). For larger JSON payloads, call mqtt.setBufferSize(1024) or similar, or the publish will silently fail.
  • QoS limits: PubSubClient publishes at QoS 0 only and can subscribe at QoS 0 or 1. If you need QoS 1 or 2 publishing, consider other libraries such as espMqttClient or arduino-mqtt, or ESP-IDF’s esp-mqtt.
  • Keep-alive: the default is 15 seconds. Adjust it with mqtt.setKeepAlive() if your network is slow or you want faster offline detection.
  • Watchdog and recovery: if the device must run unattended for months, add a watchdog and consider restarting after a long period without connectivity.
  • Battery devices: for sensors that deep-sleep, connect, publish (often with QoS 1), wait briefly for delivery, then sleep. Each Wi-Fi and TLS reconnection costs significant energy, so check whether another radio fits better. See Wi-Fi vs Bluetooth LE vs LoRa vs Zigbee.
  • Firmware updates: once devices are deployed, you’ll want to update them remotely. See Over-the-Air (OTA) Firmware Updates for IoT Devices.

The ESP-IDF alternative

If you use Espressif’s native ESP-IDF framework, its MQTT client (esp-mqtt) is event-driven and runs in its own task. It supports QoS 0, 1 and 2, TLS, and last will, and it handles reconnection automatically. A minimal setup, assuming Wi-Fi is already connected (ESP-IDF’s examples include helper code for that):

#include <stdio.h>
#include "mqtt_client.h"

static void mqtt_event_handler(void *handler_args, esp_event_base_t base,
                               int32_t event_id, void *event_data)
{
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;

    switch ((esp_mqtt_event_id_t)event_id) {
    case MQTT_EVENT_CONNECTED:
        esp_mqtt_client_publish(client, "home/esp32-demo/status", "online", 0, 1, 1);
        esp_mqtt_client_subscribe(client, "home/esp32-demo/led/set", 1);
        break;
    case MQTT_EVENT_DATA:
        printf("Topic: %.*s  Data: %.*s\n",
               event->topic_len, event->topic,
               event->data_len, event->data);
        break;
    default:
        break;
    }
}

void mqtt_start(void)
{
    const esp_mqtt_client_config_t cfg = {
        .broker.address.uri = "mqtt://192.168.1.10:1883",
        .session.last_will = {
            .topic = "home/esp32-demo/status",
            .msg = "offline",
            .qos = 1,
            .retain = 1,
        },
    };
    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);
}

This uses the configuration layout from ESP-IDF v5. Older versions used a flatter config struct, so check the example projects that ship with your installed ESP-IDF version (under examples/protocols/mqtt). Those examples also show TLS and mutual-TLS setups.

Troubleshooting

Symptom Likely cause Fix
state=-2 (connect failed) Broker unreachable: wrong IP, firewall, or Mosquitto 2.x not listening on the network Check the IP, open port 1883, add a listener 1883 line
state=5 (not authorised) Anonymous access disabled, or wrong credentials Add a username/password, or check the password file
Connects, then disconnects in a loop Two devices sharing a client ID Make client IDs unique
Publish returns false for long messages Payload larger than PubSubClient’s buffer Increase it with setBufferSize()
Commands stop arriving after a reconnect Subscriptions not renewed Subscribe inside the connect function
Frequent disconnects mqtt.loop() not called often enough, or long delay() calls Remove blocking code and call loop() every iteration
TLS connection fails Wrong CA certificate, hostname mismatch, or wrong port Verify the certificate chain, hostname and port 8883

FAQ

Can the ESP32 be an MQTT broker itself? There are small broker libraries for the ESP32, but they handle only a few clients and limited traffic. For anything beyond a small experiment, run the broker on a Raspberry Pi, a server or a cloud service, and keep the ESP32 as a client.

Do I need the internet for MQTT? No. A broker on your local network works without internet access, which also keeps your data at home. You only need the internet if the broker is in the cloud.

Which QoS should I use? QoS 0 is fine for frequent telemetry where losing an occasional reading doesn’t matter. Use QoS 1 for commands and important events. QoS 2 is rarely needed in small IoT systems, and many constrained devices skip it.

Is MQTT better than HTTP for IoT? For devices that send frequent small messages or need to receive commands at any time, MQTT is usually more efficient because it keeps one lightweight connection open and pushes messages both ways. HTTP is simpler for occasional uploads or when you’re working with existing web APIs. To see where MQTT fits in a full system, read IoT System Architecture. For more project ideas, see IoT projects using embedded systems.

The complete guide to iot and edge ai

Embedded Systems and the Internet of Things
Read the guide

Keep exploring

Guides from other topics

All topics →