All articles

    MQTT with the ESP32: Send Sensor Readings Anywhere

    MQTT explained simply: the broker, topics, publish and subscribe, designing topic names and wildcards, an ESP32 example with the PubSubClient library that sends the temperature and receives an on command, reconnecting, retain and QoS, the last-will message for device status, sending JSON, connecting to Home Assistant, monitoring tools, well-known faults, and security.

    Updated 6 min read

    A web page on the ESP32 is excellent inside the home. But if you have many devices, or want a dashboard, or to connect them to Home Assistant, the protocol the IoT world uses is MQTT: lightweight, simple, and designed for exactly this.

    The ESP32 publishes the reading to the broker, and the broker distributes it to all subscribers
    The ESP32 publishes the reading to the broker, and the broker distributes it to all subscribers

    The idea in 4 words

    • Broker: a server in the middle (such as Mosquitto). It receives messages and distributes them.
    • Topic: the message's address, such as home/livingroom/temp.
    • Publish: a device sends a message on a topic.
    • Subscribe: a device tells the broker "send me anything on this topic".

    The devices don't talk to each other directly; everything goes through the broker. So you can add a new device without changing the others.

    Why not HTTP? With HTTP the device has to ask every so often "anything new?". With MQTT the connection is always open, the message arrives instantly when sent, and the message itself is very small (bytes). That saves data and battery, and lets a button on your phone switch on the light in a fraction of a second.

    Designing topics

    • From general to specific: home/room/thing, such as home/kitchen/temp.
    • Lower-case English letters with no spaces.
    • Separate state from command: home/kitchen/light/state (the device reports its state), and home/kitchen/light/set (commands to the device).

    Wildcards in subscriptions

    SubscriptionReceives
    home/kitchen/tempExactly this topic
    home/+/tempThe temperature from every room
    home/#Anything under home

    The + is one level, and the # is everything below. These are for subscribing only, not publishing.

    An example: the ESP32 sends and receives

    The PubSubClient library:

    #include <WiFi.h>
    #include <PubSubClient.h>
    
    WiFiClient net;
    PubSubClient mqtt(net);
    const int LED = 2;
    
    void onMessage(char* topic, byte* payload, unsigned int len) {
      if (len > 0 && payload[0] == '1') digitalWrite(LED, HIGH);
      if (len > 0 && payload[0] == '0') digitalWrite(LED, LOW);
    }
    
    void reconnect() {
      while (!mqtt.connected()) {
        if (mqtt.connect("esp32-livingroom")) {
          mqtt.subscribe("home/livingroom/led");
        } else {
          delay(2000);
        }
      }
    }
    
    void setup() {
      pinMode(LED, OUTPUT);
      WiFi.begin("network-name", "password");
      while (WiFi.status() != WL_CONNECTED) delay(300);
      mqtt.setServer("192.168.1.10", 1883);   // the broker's address
      mqtt.setCallback(onMessage);
    }
    
    unsigned long last = 0;
    void loop() {
      if (!mqtt.connected()) reconnect();
      mqtt.loop();
      if (millis() - last > 10000) {
        last = millis();
        float t = 24.6;   // read the sensor here
        mqtt.publish("home/livingroom/temp", String(t, 1).c_str());
      }
    }
    • mqtt.loop() must be called constantly, so don't put a long delay in.
    • The client name must be different for each device, or the broker will disconnect one of them.

    A note on reconnect: its while loop halts the whole program until the broker comes back. If the device does something else important (such as reading a button or controlling a motor), make it one attempt every 5 seconds with millis instead of the while. And if the WiFi itself drops, WiFi.status() will tell you.

    The last will message: is the device online or not?

    The last will is a message you give the broker when connecting, and the broker publishes it by itself if the device suddenly disappears (the power goes off or the WiFi drops):

    // connect(name, user, password, will topic, QoS, retain, will message)
    if (mqtt.connect("esp32-livingroom", "user", "pass",
                     "home/livingroom/status", 1, true, "offline")) {
      mqtt.publish("home/livingroom/status", "online", true);
    }

    That way any dashboard can show online/offline for each device, and the true (retain) keeps the last state stored at the broker.

    Sending more than one reading: JSON

    Instead of a topic per reading, send everything in one message:

    char buf[80];
    snprintf(buf, sizeof(buf), "{\"temp\":%.1f,\"hum\":%.0f}", t, h);
    mqtt.publish("home/livingroom/sensor", buf);

    The result is {"temp":24.6,"hum":55}, and any dashboard or Home Assistant can read the values from it. And if the message is larger than about 256 bytes, increase the size with mqtt.setBufferSize(512), because PubSubClient rejects large messages without telling you.

    Where does the broker come from?

    • Mosquitto on a computer or a Raspberry Pi at home. This is the most common.
    • Home Assistant has a broker as an add-on.
    • Public brokers for testing (such as test.mosquitto.org): anyone can see your messages. For testing only.

    With Home Assistant: there's a feature called MQTT discovery: the ESP32 sends a configuration message once on a particular topic, and the device appears in Home Assistant by itself with its name and unit. And if you don't want to write any code at all, ESPHome does all of this with a simple configuration file.

    Useful tools

    • MQTT Explorer on the computer: see all the topics and messages.
    • Many phone apps that create buttons and graphs on topics.
    • The command line: mosquitto_sub -h 192.168.1.10 -t "home/#" -v shows every message, and mosquitto_pub sends a test message.

    Two important terms

    • Retain: the broker keeps the last message, so any newly subscribing device gets it immediately (useful for a light's state or the last reading).
    • QoS: the delivery guarantee level (0, 1 and 2). 0 is enough for readings sent every so often.

    Beware of retain with commands: if you send a "turn on the heater" command on set with retain, every time the device restarts it will receive the command again and switch on! Retain is for state, not commands.

    Well-known faults

    SymptomUsual cause
    mqtt.connect always failsWrong broker address, the port is blocked, or it needs a username and password
    It connects and disconnects repeatedlyThe client name duplicates another device's, or loop() isn't being called
    It doesn't receive commandsSubscribing before connecting, or the topic differs by a character
    Long messages don't arriveThe buffer size is too small; setBufferSize
    The device switches something on by itself after a restartA command sent with retain

    Security

    • Enable a username and password on the broker.
    • If you'll connect from outside the home, use TLS (port 8883) or a VPN, and don't open port 1883 to the internet.
    • Don't control dangerous things (heaters, locks) without real protection. See safety with household mains.

    On a battery?

    Wake, connect, publish and sleep. See ESP32 deep sleep.

    Connecting to WiFi and the broker takes a second or two at a current of about 100–150 mA, and that's what eats the battery. Reduce the number of wake-ups, and use a static IP so connecting is faster. Work out the life in battery life.

    FAQ

    Can I control it from outside the home? Yes, but don't expose the broker to the internet directly. Use a VPN into your home, or a cloud broker with TLS and a strong password, or Home Assistant Cloud.

    MQTT, Blynk or Firebase? Ready-made services are faster at first, but you're tied to them and their limits. MQTT is open, works inside the home with no external internet, and most smart home systems understand it.

    Circuits Nerd
    © 2026 Circuits Nerd. All rights reserved.