ESP32 MQTT Tutorial: Publish Sensor Data and Control an LED
Sep 29th, 2026

In this ESP32 MQTT tutorial, you will learn how MQTT enables IoT devices to exchange data without maintaining direct connections with each other. The ESP32 reads a potentiometer, publishes the reading through MQTT, and listens for commands that switch an external LED on or off.In this tutorial, an ESP32 reads a potentiometer, publishes the reading through MQTT, and listens for commands that switch an external LED on or off.
For this ESP32 MQTT example, we will use MQTT by Joel Gaehwiler rather than PubSubClient.PubSubClient is no longer maintained, while the MQTT library used here provides ESP32 support and an API for MQTT 3.1.1, QoS, retained messages, and Last Will messages.
What Is MQTT and How Does It Work with ESP32?
MQTT uses a publish/subscribe model.
Instead of sending data directly from the ESP32 to another application, both devices communicate through an ESP32 MQTT broker connection.A device or application connected to that broker is called a client.

In an ESP32 MQTT project, messages are organized by topics.In our project, suppose the unique prefix is:
sunfounder/esp32/7A3F
The ESP32 publishes the potentiometer reading to:
sunfounder/esp32/7A3F/sensor
MQTTX subscribes to that topic and receives the payload, such as:
2378
For communication in the other direction, MQTTX publishes ON or OFF to:
sunfounder/esp32/7A3F/led/set
The ESP32 subscribes to that topic and changes the LED accordingly.
This ESP32 MQTT publish subscribe structure is useful when several sensors, dashboards, controllers, or other applications need to exchange information.
Hardware and Software Requirements
This project uses:
•ESP32-WROOM-32 development board
•10 kΩ potentiometer
•LED
•220 Ω resistor
•Breadboard and jumper wires
•Arduino IDE 2.x
•ESP32 Arduino Core 3.3.8
•MQTT by Joel Gaehwiler 2.5.3
•MQTTX Desktop
•Wi-Fi network with Internet access
If the ESP32 is not yet configured in Arduino IDE, follow the SunFounder ESP32 board installation guide first.
In Arduino IDE, open Library Manager, search for MQTT, and install the library by Joel Gaehwiler.
Wiring

The potentiometer's two outer pins connect to 3.3 V and GND. Its center pin connects to GPIO34. For more details on improving analog reading accuracy, see SunFounder’s ESP32 ADC calibration guide.For ESP32 MQTT LED control, connect GPIO23 through the 220 Ω resistor to the LED anode and connect the LED cathode to GND.
Prepare the MQTT Broker and MQTTX
For this beginner project, use the public Eclipse Mosquitto test broker:
•Host: test.mosquitto.org
•Port: 1883
•Protocol: MQTT
•MQTT version: 3.1.1
•Username: none
•Password: none
•TLS: disabled
IMPORTANT: In this public ESP32 MQTT broker setup, port 1883 is intentionally unencrypted and does not require authentication.It is suitable for experimentation, not private or production data.
To test ESP32 MQTT with MQTTX, open MQTTX and create a connection with those settings. Give MQTTX its own client ID, for example:
mqttx-7A3F
The ESP32 will generate a different client ID from its MAC address.


For your ESP32 MQTT project, replace 7A3F in the sketch with your own random letters and numbers.Do not use the example prefix unchanged. A unique prefix prevents different people using the public broker from accidentally controlling each other's projects.
Build the ESP32 MQTT Project
To build this ESP32 MQTT example, install the MQTT by Joel Gaehwiler library and upload the complete sketch below:
The ESP32 MQTT reconnection code does not trap the ESP32 in an endless MQTT connection loop. Wi-Fi and MQTT are checked separately, and another attempt is made after five seconds when either connection fails.
After an MQTT reconnection, the ESP32 subscribes to the LED command topic again. This is important because subscriptions cannot simply be assumed to remain available after a new clean connection.
Test Publishing and Subscribing
1.Open Serial Monitor at 115200 baud.
Once connected, output should resemble:

2.In MQTTX, subscribe to: sunfounder/esp32/7A3F/#
To test the ESP32 MQTT publish subscribe workflow, first open Serial Monitor at 115200 baud.

You should see ESP32 MQTT sensor data arrive in MQTTX every five seconds.
To control the LED, publish: ON to: sunfounder/esp32/7A3F/led/set

Use QoS 1 and leave Retain disabled.
The LED should turn on. Send OFF to switch it off.

MQTT QoS, Retained Messages, and Last Will
ESP32 MQTT QoS supports three Quality of Service levels for different message delivery requirements.
•QoS 0 means “at most once.” There is no delivery acknowledgement. We use it for frequent potentiometer readings because losing an occasional reading is not important.
•QoS 1 means “at least once.” Delivery is acknowledged, although duplicates are possible. The LED subscription uses QoS 1.
•QoS 2 provides “exactly once” delivery with additional protocol overhead. It is unnecessary for this simple project.
In this ESP32 MQTT setup, the status message is retained so a new subscriber can immediately discover whether the ESP32 last reported itself online.
LED commands are deliberately not retained. If an ON command were retained, the broker could send that old command again as soon as the ESP32 resubscribed after a restart. For beginners, commands that trigger hardware should generally not be retained unless replaying the last requested state is intentional.
The ESP32 MQTT sketch also configures a Last Will. If the ESP32 unexpectedly loses its connection, the broker can publish offline to the status topic.
Basic MQTT Security
The public ESP32 MQTT broker used in this project is intended only as a learning environment. Port 1883 provides neither encryption nor authentication, so never publish passwords, personal information, API keys, or real device data through these tutorial topics.
A private ESP32 MQTT broker deployment should normally require authentication and TLS. The ESP32 should connect through WiFiClientSecure, validate the broker's server certificate against a trusted CA certificate, and use credentials or another controlled authentication method.
For a secure ESP32 MQTT connection, TLS encryption without certificate verification is not sufficient.verification is what allows the client to confirm that it is communicating with the intended server.
Common ESP32 MQTT Problems
| Problem | Likely cause | Check |
|---|---|---|
| ESP32 cannot connect | Wi-Fi, hostname, or port is wrong | Verify Wi-Fi and test.mosquitto.org:1883 |
| Connection repeatedly drops | Duplicate client ID | Give every MQTT client a unique ID |
| MQTTX receives nothing | Topic mismatch | Compare the complete topic strings |
| Some sensor readings are missing | QoS 0 delivery | Occasional loss is allowed at QoS 0 |
| LED does not respond | Wrong command topic or payload | Use the exact topic and ON/OFF |
| LED stops responding after reconnect | Subscription was not restored | Subscribe again after MQTT reconnect |
| Unexpected LED action after reconnect | Command was retained | Disable Retain for command messages |
Once this ESP32 MQTT example is working, the same structure can be reused for temperature sensors, environmental monitors, relays, displays, and other ESP32 IoT devices. The sensor and actuator may change, but the MQTT pattern remains the same: connect, publish measurements, subscribe to commands, and recover cleanly when the network disappears.
Conclusion
In this ESP32 MQTT tutorial, you built a complete two-way IoT project: the ESP32 publishes potentiometer readings, receives LED control commands, and reports its connection status using retained messages and a Last Will. You also learned how MQTT topics, QoS levels, reconnection logic, and public-broker security affect a real project. The same structure can easily be extended to temperature sensors, relays, dashboards, and home automation systems. For a production deployment, replace the public test broker with a private broker that uses authentication, TLS encryption, certificate verification, and unique topics for every device.
Frequently Asked Questions
Can ESP32 use MQTT?
Yes. ESP32 MQTT communication allows the board to connect to an MQTT broker over Wi-Fi and publish or subscribe to messages using an MQTT client library. This makes it suitable for sensors, remote controls, dashboards, and home automation projects.
Does ESP32 MQTT require an Internet connection?
Not necessarily. An ESP32 MQTT connection only requires Internet access when using a public or cloud broker.If the broker runs on a Raspberry Pi, computer, or server on the same local network, the ESP32 can communicate with it without Internet access.
Which MQTT library should I use with ESP32?
For an ESP32 MQTT Arduino IDE project, this tutorial uses the MQTT library by Joel Gaehwiler. It supports MQTT 3.1.1, QoS levels, retained messages, Last Will messages, and ESP32-compatible network clients.
Which MQTT QoS level is best for ESP32?
QoS 0 is usually suitable for frequent sensor readings where occasional data loss is acceptable. QoS 1 is more appropriate for control commands and important status messages. QoS 2 adds more overhead and is rarely necessary for simple ESP32 projects.
Why is MQTTX not receiving data from my ESP32?
When troubleshooting ESP32 MQTT with MQTTX, check that the ESP32 and MQTTX are connected to the same broker and that the complete topic strings match. Also verify the topic prefix, Wi-Fi connection, MQTT subscription, and client IDs. Even a small difference in capitalization or slashes creates a different MQTT topic.
Should MQTT commands be retained?
For ESP32 MQTT LED control, hardware commands generally should not be retained unless replaying the last requested state is intentional.Otherwise, an old retained ON command could be delivered again when the ESP32 reconnects and subscribes.
Is test.mosquitto.org safe for ESP32 projects?
It is suitable for learning and temporary testing, but port 1883 is public, unencrypted, and unauthenticated. Do not transmit passwords, API keys, personal information, or sensitive device data. Production projects should use a private broker with authentication, TLS, and certificate verification.
Can multiple ESP32 boards use the same MQTT broker?
Yes. Multiple boards can use the same ESP32 MQTT broker, but each ESP32 should have a unique MQTT client ID and its own topic prefix. such as home/esp32/device01 or home/esp32/device02. This prevents client disconnections, topic collisions, and accidental control of the wrong device.
