💡 Electron Parade
← Back to Academy

You know that special kind of hell where you try to get two ESP32s to talk to each other using raw HTTP requests? Yeah, we’ve all been there. You write a script for one board to send a temperature reading to the other, but your Wi-Fi hiccups for 0.4 seconds, the request hangs, the magic blue smoke of frustration fills the room, and suddenly your microcontroller is stuck in an infinite loop contemplating the meaning of its own existence while your plants dry out.

It’s like trying to have a conversation by writing a letter, putting it in a bottle, throwing it into the ocean, and just hoping your buddy on the other island finds it. It’s terrible, it’s slow, and honestly, we’re better than this.

Enter MQTT (Message Queuing Telemetry Transport). It’s the lightweight, lightning-fast, “no-nonsense” protocol that actually makes the Internet of Things function like an internet instead of a bunch of isolated microcontrollers shouting into the void.

If HTTP is the postal service, MQTT is a massive group chat. Let’s learn how it works.


What is MQTT and Why Do We Need It?

MQTT is a publish-subscribe (pub/sub) messaging protocol designed specifically for devices with limited processing power and sketchy network connections.

Instead of Board A connecting directly to Board B, both boards connect to a central server called a Broker (like a Mosquitto server running on a Raspberry Pi or a cloud service).

The Pub/Sub Model:

  1. The Broker: The traffic cop. It receives all messages and routes them to anyone who asked to hear them.
  2. Publishing: A device (like a temperature sensor) yells out a message to a specific “Topic” (e.g., home/livingroom/temperature).
  3. Subscribing: Another device (like a smart display) tells the Broker, “Hey, let me know whenever someone posts to home/livingroom/temperature.”

When the sensor publishes the data, the Broker instantly forwards it to the display. If a new device (like a phone app) wants the data, it just subscribes to the same topic. The sensor doesn’t care; it just keeps doing its job.

Gear You’ll Need

To get started with MQTT on an ESP32, you’ll need some basic hardware:

Setting Up the Code

We’ll use the PubSubClient library by Nick O’Leary, which is the gold standard for Arduino/ESP32 MQTT projects.

Here is a basic snippet to get your ESP32 publishing temperature data to an MQTT topic:

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"

// Network details
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// MQTT Broker details
const char* mqtt_server = "192.168.1.100"; // Your broker IP
const char* mqtt_topic = "home/office/temp";

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(4, DHT11); // DHT11 on GPIO 4

void setup() {
  Serial.begin(115200);
  dht.begin();
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  client.setServer(mqtt_server, 1883);
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect with a random client ID
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // Publish every 10 seconds
  static unsigned long lastMsg = 0;
  unsigned long now = millis();
  if (now - lastMsg > 10000) {
    lastMsg = now;
    
    float t = dht.readTemperature();
    if (!isnan(t)) {
      char tempString[8];
      dtostrf(t, 1, 2, tempString);
      Serial.print("Publishing temperature: ");
      Serial.println(tempString);
      
      // Publish to the topic!
      client.publish(mqtt_topic, tempString);
    }
  }
}

Next Steps

Now that your ESP32 is publishing, you can use software like Node-RED, Home Assistant, or a simple Python script to subscribe to home/office/temp and do whatever you want with the data. Welcome to the real Internet of Things.

In the next lesson, we’ll dive into ESP-NOW for when you don’t even have a Wi-Fi router to rely on!