Skip to content
Free Delivery on Orders Above Rs 999/- Pan-India
Cash on Delivery Available for Orders above Rs.500/- and Upto Rs 3000/-
SAVE more when you BUY more. Upto 30% Off on BULK PURCHASE
GST Invoices for Your Business
Dedicated Technical Support Team
Safely Delivering Genuine Products PAN INDIA
Delivering to
Select Location ▾
Delivering to Select Location
▾

MQTT Explained: ESP32 MQTT Tutorial Step by Step

MQTT Explained: ESP32 MQTT Tutorial Step by Step
-
Written By - Robocraze -
📅 Updated on 04 Dec 2026
✨ Summarize with AI
✅ Prompt copied

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).

Diagram of the MQTT publish-subscribe model: an ESP32 with a DHT11 publishes a temperature reading to a broker, which forwards it to a phone app, a Node-RED dashboard and Home Assistant.

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.

MQTT topic tree showing robocraze, room1 and room2, each with temp and humidity topics, with examples of the + and # wildcards.

Components and Supplies

🔥 Trending
ESP32 NodeMCU (38-Pin) WiFi + BLE – Ideal for IoT. -Nodemcu ESP Board -RobocrazeESP32 NodeMCU (38-Pin) WiFi + BLE – Ideal for IoT. -Nodemcu ESP Board -Robocraze

    ESP32 38-Pin WiFi + Bluetooth NodeMCU Development Board

    ESP32 38-Pin WiFi + Bluetooth NodeMCU Development Board The ESP32 38-Pin WiFi + Bluetooth NodeMCU Development Board is a versatile microcontroller development board designed for IoT, home automation, robotics, embedded systems, and wireless electronics projects. Built around the ESP-WROOM-32 module, it combines a powerful...
    Rs 455/-
    Rs 455/-
    Rs 599/-
    Save Rs 144/-
    DHT11 Humidity and Temperature Sensor Module – Compact DHT11 module for temperature and humidity detection -RobocrazeDHT11 Humidity and Temperature Sensor Module – Compact DHT11 module for temperature and humidity detection -Robocraze

      DHT11 Humidity and Temperature Sensor Module

      DHT11 Humidity and Temperature Sensor Module The DHT11 Humidity and Temperature Sensor Module, commonly referred to as the dht11 sensor, is capable of sensing both temperature as well as humidity. This makes it ideal for DIY electronics projects and automation systems using platforms like...
      Rs 62/-
      Rs 62/-
      Rs 99/-
      Save Rs 37/-
      MB102 830 Points Solderless Breadboard for Arduino & DIY Projects - Electronic Components -RobocrazeMB102 830 Points Solderless Breadboard for Arduino & DIY Projects - Electronic Components -Robocraze

        MB102 830 Points Solderless Breadboard

        MB102 830 Points Solderless Breadboard  The MB102 830 point breadboard is an exceptional tool for experimenting with circuit designs, whether in an R&D facility or a university lab. This full size breadboard is designed to help you quickly build temporary circuits for testing or...
        Rs 69/-
        Rs 69/-
        Rs 99/-
        Save Rs 30/-

        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

        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.

        Shop now →


        DHT11 Humidity and Temperature Sensor Module

        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.

        Shop now →


        MB102 830 Points Solderless Breadboard

        MB102 830 Points Solderless Breadboard

        830 tie points with power rails on both sides, so the ESP32 and sensor fit side by side.

        Shop now →


        7Semi ESP32-S3-Dev-BoardC-1-N8R8 (optional upgrade)

        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.

        Shop now →


        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

        Wiring diagram connecting a DHT11 module to an ESP32: VCC to 3V3, GND to GND and DATA to GPIO4.

        Step 2: Install the libraries

        1. We add ESP32 support to the Arduino IDE: we open Boards Manager, search for esp32, and install esp32 by Espressif Systems.

        2. In Library Manager, we install PubSubClient by Nick O'Leary. This is the MQTT client.

        3. 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.

        Sequence diagrams of MQTT QoS 0 with one PUBLISH, QoS 1 with PUBLISH and PUBACK, and QoS 2 with PUBLISH, PUBREC, PUBREL and PUBCOMP.

        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.

        
        

        Excerpt

        Learn what MQTT is, how brokers and topics work, and how it compares with HTTP. Then follow our step-by-step ESP32 MQTT tutorial with a DHT11 sensor.

        Frequently Asked Questions

        What is MQTT used for?

        MQTT is used to move small, frequent messages between connected devices: sensor readings, device status and remote commands. It appears in home automation, industrial monitoring, fleet tracking and connected appliances.

        Is MQTT better than HTTP for IoT?

        For most sensor and control projects, yes. MQTT keeps one connection open, uses tiny headers and pushes commands to devices instantly. HTTP is simpler when a device sends data rarely or must call an existing REST API.

        What is an MQTT broker?

        An MQTT broker is the server that receives every published message and forwards it to the clients subscribed to that topic. Mosquitto, HiveMQ and EMQX are common examples.

        Can an ESP32 be an MQTT broker?

        Yes, for small setups. Libraries such as PicoMQTT turn an ESP32 into a basic broker for a handful of clients on a local network. For more devices or long-term use, we recommend Mosquitto on a Raspberry Pi or PC.

        What port does MQTT use?

        Unencrypted MQTT uses port 1883 and MQTT over TLS uses port 8883. Some brokers also offer MQTT over WebSockets on ports such as 8080 or 8083 for browser clients.

        Is MQTT secure?

        MQTT itself does not encrypt anything, but brokers support TLS encryption, usernames and passwords, and per-topic access control. Use port 8883 with TLS and authentication for any project that leaves your home network.

        Prev Post
        Next Post

        Leave a comment

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

        Thanks for subscribing!

        This email has been registered!

        Shop the look

        Choose Options

        Edit Option
        Back In Stock Notification

        Choose Options

        this is just a warning
        Login
        Shopping Cart
        0 items
        FREE SHIPPING!
        ₹100 OFF
        ₹200 OFF
        ₹999
        ₹2500
        ₹4900
        WhatsApp Chat Chat