Introduction
MQTT is the backbone of modern IoT communication. It is a lightweight publish-subscribe protocol perfect for the ESP32. In this tutorial we connect to a free public broker, publish sensor data, and receive control commands.
MQTT Architecture
- Broker: Central server routing messages (e.g. broker.hivemq.com).
- Publisher: ESP32 sending sensor readings to a topic.
- Subscriber: Dashboard or phone receiving the data.
Required Libraries
Install via Arduino IDE Library Manager: PubSubClient by Nick O’Leary and DHT sensor library by Adafruit.
Complete Code
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
void callback(char* topic, byte* payload, unsigned int len) {
String msg = ""; for (int i=0;i<len;i++) msg+=(char)payload[i];
Serial.println("Received: " + msg);
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Client")) { client.subscribe("home/control"); }
else delay(5000);
}
}
void setup() {
Serial.begin(115200); dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnect(); client.loop();
float t = dht.readTemperature(), h = dht.readHumidity();
if (!isnan(t)) {
String p = "{\"t\":" + String(t) + ",\"h\":" + String(h) + "}";
client.publish("home/sensors", p.c_str());
}
delay(5000);
}
Testing
Download MQTT Explorer, connect to broker.hivemq.com:1883 and subscribe to home/sensors. You will see live readings every 5 seconds!
Conclusion
MQTT is the most efficient IoT protocol. Once mastered, you can connect dozens of sensors feeding into Node-RED or Home Assistant dashboards in real time.