ESP32 MQTT Connection Fails to Broker
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about ESP32 MQTT Connection Fails to Broker. We cover key concepts, practical examples, and best practices.
The Problem
ESP32 cannot connect to MQTT broker — connection refused, timeout, or unauthorized.
Quick Fix
Wrong
WiFiClient espClient;
PubSubClient client(espClient);
client.setServer("broker.emqx.io", 1883);
client.connect("esp32");
Attempting MQTT connection... failed, rc=-2 try again
Right
WiFiClient espClient;
PubSubClient client(espClient);
client.setKeepAlive(60);
int retries = 0;
while (!client.connected() && retries < 5) {
if (client.connect("esp32-client", "user", "pass")) {
Serial.println("Connected");
} else {
Serial.printf("Failed rc=%d", client.state());
retries++; delay(5000);
}
}
Connected to MQTT broker
rc=0 means success
Prevention
Check return code: 0=success, 1=bad protocol, 2=ID rejected, 3=unavailable, 4=bad credentials, 5=not authorized. Set unique client ID. Add authentication for production. Use setKeepAlive(60).
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro