Learn ESP32 MQTT step by step! Master ESP32 MQTT client, broker, dashboards, MicroPython, Arduino IDE, Home Assistant, AWS IoT, and more with real examples and beginner-friendly tutorials.
Introduction to ESP32 MQTT
If you’re exploring IoT projects, chances are you’ve come across ESP32 MQTT. It’s one of the most reliable ways to send sensor data, control devices, and integrate your microcontroller with dashboards or cloud services. In this guide, we’ll cover everything from ESP32 MQTT client examples to secure AWS IoT integration.
Think of this article as a conversation with a smart friend over coffee—clear, friendly, and practical.
What is ESP32 and Why MQTT?
The ESP32 is a powerful microcontroller with Wi-Fi and Bluetooth, perfect for IoT devices. MQTT is a lightweight messaging protocol that works on a publish-subscribe model, making it ideal for ESP32 projects where bandwidth and power are limited.
Using ESP32 MQTT provides:
- Real-time data updates
- Low bandwidth usage
- Easy integration with platforms like Home Assistant or AWS
- Secure communication with authentication
Setting Up Your ESP32 for MQTT
To get started:
- Hardware Needed: ESP32 board, USB cable, Wi-Fi network
- Software Needed: Arduino IDE or MicroPython environment
- MQTT Broker Options:
- Public brokers:
broker.hivemq.com - Private broker: Mosquitto server
- Cloud broker: AWS IoT, Adafruit IO
- Public brokers:
Pro Tip: Beginners should start with public brokers before moving to cloud or secure servers.
Installing ESP32 MQTT Libraries
For Arduino IDE:
- PubSubClient → Most used for ESP32 MQTT client
- Adafruit MQTT Library → For dashboards and cloud services
- AsyncMqttClient → Non-blocking, asynchronous communication
Installation Steps:
- Open Arduino IDE → Tools → Manage Libraries
- Search for your library (e.g.,
PubSubClient) - Click Install
For ESP32 MQTT Async, install AsyncMqttClient for advanced asynchronous tasks.
ESP32 MQTT Client Example
Here’s a simple ESP32 MQTT Arduino code example that connects to a broker and sends a message:
#include
#include
const char* ssid = "YourWiFi";
const char* password = "YourPassword";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
while (!client.connect("ESP32Client")) {
Serial.print("Connecting...");
delay(1000);
}
Serial.println("Connected to MQTT broker");
}
client.publish("esp32/test", "Hello from ESP32");
delay(2000);
}
This example demonstrates ESP32 MQTT broker and client communication.
ESP32 MQTT with DHT11 Sensor
For home automation, sending sensor data is crucial. Here’s ESP32 MQTT DHT11 example:
#include
#define DHTPIN 4
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
char payload[50];
sprintf(payload, "Temperature: %.2f, Humidity: %.2f", t, h);
client.publish("esp32/dht11", payload);
delay(5000);
}
This data can be displayed on ESP32 MQTT dashboard like Adafruit IO or Home Assistant.
ESP32 MQTT Home Assistant Integration
Home Assistant is perfect for controlling devices using ESP32 MQTT. Steps:
- Configure MQTT broker in Home Assistant
- Set up topics (e.g.,
esp32/livingroom/light) - ESP32 publishes messages (
ON/OFF) - Home Assistant automates responses
Using ESP32 MQTT discovery, devices can auto-register without manual configuration.
ESP32 MQTT AWS Integration
For cloud-based IoT, ESP32 MQTT AWS is reliable:
- Create an AWS IoT Thing
- Download certificates for secure connection
- Use libraries like Adafruit MQTT to connect
- Publish or subscribe to MQTT topics
If you’re also exploring real-time web communication along with MQTT, this guide on ESP32 WebSocket tutorials
This helps you understand how WebSockets and MQTT can work together in an IoT workflow. AWS ensures ESP32 MQTT authentication and encrypted communication.
ESP32 MQTT MicroPython Example
Prefer Python? Micropython ESP32 MQTT is simple:
import network
from umqtt.simple import MQTTClient
ssid = "YourWiFi"
password = "YourPassword"
mqtt_server = "broker.hivemq.com"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
client = MQTTClient("esp32_client", mqtt_server)
client.connect()
client.publish(b"esp32/test", b"Hello from MicroPython")
This allows quick prototyping without complex setup.
ESP32 MQTT AT Commands
Some ESP32 boards support AT commands for MQTT:
AT+MQTTCONN="broker",1883→ ConnectAT+MQTTPUB="topic","message"→ PublishAT+MQTTSUB="topic"→ Subscribe
This is useful when controlling ESP32 via serial interface.
ESP32 MQTT with W5500
For Ethernet-based ESP32 projects, W5500 ESP32 MQTT works well:
#include
#include
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);
EthernetClient ethClient;
PubSubClient client(ethClient);
void setup() {
Ethernet.begin(mac, ip);
client.setServer("broker.hivemq.com", 1883);
}
Great for projects without Wi-Fi.
ESP32 FreeRTOS MQTT Example
Advanced users can run MQTT in FreeRTOS tasks:
void mqttTask(void *pvParameters) {
for(;;) {
if(!client.connected()) {
client.connect("ESP32Client");
}
client.publish("esp32/freertos", "Hello from FreeRTOS task");
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
void setup() {
xTaskCreate(mqttTask, "MQTT", 4096, NULL, 1, NULL);
}
This allows ESP32 to multitask efficiently.
Security Tips for ESP32 MQTT
- Use username/password authentication
- Enable TLS/SSL for encryption
- Unique client IDs prevent conflicts
- AWS IoT or self-signed certificates for production
ESP32 MQTT Dashboards
Popular dashboards include:
- Adafruit IO: Simple, beginner-friendly
- ThingsBoard: Advanced visualizations
- Home Assistant: Automation-focused
- Node-RED: Flow-based programming
Dashboards help monitor sensors and control devices in real-time .
ESP32 MQTT Troubleshooting Guide
1. Why is my ESP32 MQTT client not connecting to the broker?
The most common reason is incorrect MQTT broker details. Check the broker IP, port, and authentication settings. Some brokers require TLS, and if your esp32 mqtt client is not configured for it, the connection will fail.
2. Why does my ESP32 MQTT keep disconnecting?
This usually happens due to unstable Wi-Fi or incorrect keep-alive settings. Try increasing the keep-alive interval and ensure your router does not block frequent reconnect attempts.
3. My ESP32 MQTT example works, but custom code fails—why?
Custom code may miss essential functions like reconnect handling or loop processing. Compare your logic with a stable esp32 mqtt example from an official library like PubSubClient.
4. Why is the ESP32 MQTT broker not receiving published messages?
Incorrect topic names are the most common issue. MQTT topics are case-sensitive. Check for typos and verify that both broker and esp32 mqtt client use the same structure.
5. Why are my ESP32 MQTT subscribe callbacks not triggering?
If the callback function is not firing, verify the subscription result in logs. Also check if the esp32 mqtt broker supports retained messages or if QoS is mismatched.
6. How do I fix ESP32 MQTT authentication failures?
Authentication failures occur when your username or password is incorrect. If you’re using Home Assistant or AWS IoT, ensure you’re using proper tokens or certificates supported by esp32 mqtt authentication.
7. Why does my ESP32 MQTT dashboard not update in real time?
Dashboards like Adafruit IO and ThingsBoard require correct feed/topic settings. Make sure your esp32 mqtt client publishes data with the exact feed key or topic format expected by the dashboard.
8. Why isn’t DHT11 data showing up through ESP32 MQTT?
If esp32 mqtt dht11 values are missing, check sensor wiring and confirm the delay between reads. DHT11 requires proper timing, and wrong delays can block MQTT publishing.
9. Can network issues affect ESP32 MQTT async performance?
Yes. When using esp32 mqtt async libraries, slow networks or packet loss can delay callbacks. Ensure your network latency is low and the async MQTT library is updated.
10. Why does W5500 with ESP32 MQTT fail to publish?
When using a W5500 Ethernet module, ensure the SPI pins are correctly mapped. If the Ethernet connection fails, the esp32 mqtt client cannot reach the broker. Check DHCP or static IP configuration.
11. Why is the ESP32 MQTT AT command mode not working?
If you’re using esp32 mqtt AT commands, make sure your ESP32 firmware supports MQTT. Some AT firmware versions do not include MQTT features and need an update.
12. Why does my ESP32 MQTT server fail to handle multiple clients?
An esp32 mqtt server or broker running locally may hit memory limits. Use a lightweight broker like Mosquitto and avoid large retained messages or high-frequency publishes.
13. Why is MicroPython ESP32 MQTT slower than Arduino IDE?
micropython esp32 mqtt runs through an interpreter, which is naturally slower than compiled code. If timing is critical, switch to Arduino IDE or use esp32 freertos mqtt example for better task management.
14. How do I check if my ESP32 MQTT documentation settings are correct?
If your setup fails, revisit your esp32 mqtt documentation and compare your Wi-Fi, broker URL, port, QoS, and topic settings. A single missing parameter can break the whole flow.
FAQs: ESP32 MQTT Tutorials
Q1: What is the difference between ESP32 MQTT broker and client?
A: In MQTT, the broker manages the distribution of messages, while the client publishes or subscribes to topics. Your ESP32 can act as a client, sending sensor data, or even as a lightweight ESP32 MQTT broker in small local setups.
Q2: Can ESP32 MQTT work with AWS IoT?
A: Yes, ESP32 MQTT AWS integration is fully supported. You can connect your ESP32 to AWS IoT using secure certificates, publish sensor data, and subscribe to control topics in real-time.
Q3: Can I use MicroPython for ESP32 MQTT?
A: Absolutely! Micropython ESP32 MQTT makes coding easy and beginner-friendly. It’s perfect for rapid prototyping and allows you to send messages to an MQTT broker without complex Arduino IDE setup.
Q4: How do I visualize ESP32 MQTT data?
A: You can create dashboards using Adafruit IO, ThingsBoard, or Home Assistant. For example, ESP32 MQTT DHT11 sensor data can be plotted live, giving you temperature and humidity updates in real-time.
Q5: Is ESP32 MQTT secure?
A: Yes, ESP32 MQTT authentication ensures secure communication. You can use username/password, TLS/SSL encryption, or certificates (for AWS IoT) to protect your data.
Q6: What is a good ESP32 MQTT library to use?
A: For Arduino IDE, PubSubClient is popular and beginner-friendly. For asynchronous communication, ESP32 MQTT Async library is ideal. Adafruit MQTT Library works great if you plan to integrate with Adafruit IO dashboards.
Q7: Can ESP32 act as both broker and client?
A: Yes, for small local networks, your ESP32 can serve as an ESP32 MQTT broker and client, handling message distribution while also sending or receiving sensor data.
Q8: How do I integrate ESP32 MQTT with Home Assistant?
A: Configure your MQTT broker in Home Assistant, set topics (like esp32/livingroom/light), and publish commands from your ESP32. Using ESP32 MQTT discovery, Home Assistant can auto-detect devices without manual configuration.
Q9: Can I use Ethernet with ESP32 MQTT instead of Wi-Fi?
A: Yes, using W5500 ESP32 MQTT modules, you can connect your ESP32 via Ethernet and publish/subscribe messages to an MQTT broker reliably, perfect for environments with unstable Wi-Fi.
Q10: How do I publish sensor data from ESP32 using MQTT?
A: Use your ESP32 MQTT client to read sensors like DHT11 or DHT22, format the data, and publish it to a topic. Example: client.publish("esp32/dht11", payload). Dashboards can then visualize it.
Q11: Can I run ESP32 MQTT with FreeRTOS?
A: Yes, you can run ESP32 FreeRTOS MQTT example tasks in parallel with other operations. This allows your ESP32 to multitask efficiently while sending and receiving MQTT messages asynchronously.
Q12: What are the best practices for ESP32 MQTT projects?
A: Ensure Wi-Fi is stable, use unique client IDs, enable ESP32 MQTT authentication, handle reconnections, and test your broker and topics with tools like MQTT Explorer before integrating dashboards.
Q13: Can ESP32 MQTT work with Arduino IDE and AT commands?
A: Yes, some ESP32 boards support ESP32 MQTT AT commands. You can connect, publish, and subscribe over serial without programming directly, useful for lightweight applications.
Q14: How do I debug ESP32 MQTT issues?
A: Check Wi-Fi connectivity first. Use serial prints in Arduino IDE to monitor MQTT connection status, subscription, and message publishing. Also, verify broker IP, port, and authentication credentials.
Mr. Raj Kumar is a highly experienced Technical Content Engineer with 7 years of dedicated expertise in the intricate field of embedded systems. At Embedded Prep, Raj is at the forefront of creating and curating high-quality technical content designed to educate and empower aspiring and seasoned professionals in the embedded domain.
Throughout his career, Raj has honed a unique skill set that bridges the gap between deep technical understanding and effective communication. His work encompasses a wide range of educational materials, including in-depth tutorials, practical guides, course modules, and insightful articles focused on embedded hardware and software solutions. He possesses a strong grasp of embedded architectures, microcontrollers, real-time operating systems (RTOS), firmware development, and various communication protocols relevant to the embedded industry.
Raj is adept at collaborating closely with subject matter experts, engineers, and instructional designers to ensure the accuracy, completeness, and pedagogical effectiveness of the content. His meticulous attention to detail and commitment to clarity are instrumental in transforming complex embedded concepts into easily digestible and engaging learning experiences. At Embedded Prep, he plays a crucial role in building a robust knowledge base that helps learners master the complexities of embedded technologies.













