MQTT is the lightweight publish/subscribe protocol that powers most DIY IoT. This ESP32 MQTT tutorial takes you from a blank sketch to a board that publishes a sensor reading and listens for commands – using the Arduino IDE and the popular PubSubClient library.
What you need
- An ESP32 board (an ESP32-S3 with a display works great and shows live values)
- Arduino IDE with the ESP32 board package installed
- The PubSubClient library
- An MQTT broker (local Eclipse Mosquitto, or a free cloud broker)
Step 1 – Install the libraries
Open Library Manager and install PubSubClient by Nick O’Leary. Confirm your ESP32 board appears under Tools > Board. This single dependency handles the MQTT handshake for you.
Step 2 – Connect to Wi-Fi
Set your credentials and call WiFi.begin(ssid, password). Wait for WL_CONNECTED before doing anything network-related – a common beginner bug is publishing before Wi-Fi is up.
Step 3 – Configure the broker
Create a WiFiClient and a PubSubClient, then client.setServer(broker_host, 1883). Give each device a unique client ID so the broker can tell them apart.
Step 4 – Publish a reading
In loop(), read a sensor and call client.publish("sensors/temp", payload). Keep the payload small – a number or a short JSON string is ideal. Remember to call client.loop() often so the client services incoming traffic and keeps the connection alive.
Step 5 – Subscribe to commands
Call client.subscribe("device/cmd") and implement the callback. When a message arrives you can flip a GPIO, change a mode, or reply on another topic. This two-way link is what turns a sensor into a controllable device.
Troubleshooting
If the connection drops, make your loop non-blocking and add a short-delayed reconnect instead of resetting the chip. For secure deployments use WiFiClientSecure on port 8883. Boards with more RAM, like the ESP32-S3 family, handle TLS comfortably.
For more board choices, see our ESP32 dev board guides.
Frequently asked questions
Which MQTT broker works with the ESP32?
Any standard broker works: Eclipse Mosquitto, HiveMQ, EMQX, or a free cloud broker. The ESP32 just needs the broker host, port and (optionally) credentials. Port 1883 is plain MQTT; 8883 is MQTT over TLS.
Can the ESP32 do MQTT over TLS?
Yes. Use WiFiClientSecure instead of WiFiClient and provide the broker certificate (or skip verification for testing). TLS adds memory cost, so a board with more RAM like the ESP32-S3 is comfortable.
Why does my ESP32 MQTT connection keep dropping?
Usually a blocking loop or a watchdog reset. Keep your loop non-blocking, call client.loop() frequently, and implement a reconnect with a short delay rather than a hard reset.
Leave a Reply