๐Ÿ“ถ
IoT

MQTT with ESP32: Building IoT Projects That Actually Work

MQTT is the backbone of most IoT projects. Setup, best practices, and reconnection handling for ESP32.

March 2, 2025ยท7 min read
โ† All articles

How MQTT Works

MQTT uses a publish/subscribe model. A broker routes messages. Publishers send to topics. Subscribers receive from topics. Topics are hierarchical: home/bedroom/temperature. Wildcards: + for one level, # for all remaining.

QoS Levels

  • โ–ธQoS 0 โ€” Fire and forget. Use for frequent sensor readings.
  • โ–ธQoS 1 โ€” Delivered at least once. Use for important events.
  • โ–ธQoS 2 โ€” Exactly once. Slowest. Use for critical commands.

Topic Design Best Practices

  • โ–ธhome/living_room/temperature โ€” by location
  • โ–ธdevices/esp32_001/sensors/temp โ€” by device
  • โ–ธcommands/bedroom/fan โ€” commands separate from telemetry

Reconnection Handling

The most common mistake: not handling disconnections. WiFi drops. Brokers restart. Implement reconnect with exponential backoff and re-subscribe to all topics after reconnecting.

๐Ÿ’ก Tip: For production: use TLS/SSL (port 8883), unique credentials per device, and ACLs to limit what each device can publish/subscribe.

๐Ÿ“ถ

Ready to try it?

Free to use โ€” no credit card required.

Generate ESP32 IoT Code โ†’