ESP32 microcontroller with MQTT (Message Queuing Telemetry Transport)

ESP32 with MQTT (Message Queuing Telemetry Transport) is a powerful combination used for IoT applications, enabling efficient communication between devices over the internet or a local network. MQTT is a lightweight, publish-subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks.

Key Concepts of MQTT

1. Broker (Server)

  • The MQTT broker acts as a central hub that manages messages between clients.
  • Popular brokers include Mosquitto, HiveMQ, and EMQX.
  • It ensures efficient message distribution between publishers and subscribers.

2. Client

  • Any device that connects to the broker (ESP32, Raspberry Pi, PC, etc.).
  • It can be a Publisher, Subscriber, or both.

3. Topics

  • Messages are sent to specific topics.
  • Clients subscribe to topics to receive relevant messages.
  • Topics follow a hierarchy, e.g., home/livingroom/temperature.

4. QoS (Quality of Service) Levels

  • QoS 0: “At most once” (fire and forget).
  • QoS 1: “At least once” (message is delivered at least once but may be duplicated).
  • QoS 2: “Exactly once” (ensures message is received only once).

ESP32 as an MQTT Client:

The ESP32 can act as both a publisher (sending data to the broker) and a subscriber (receiving data from the broker).

Libraries Required

For ESP32, the most commonly used MQTT library in Arduino IDE.

#include <WiFi.h>

#include <PubSubClient.h>

Basic ESP32 MQTT Setup

1. Install Mosquitto Broker (Optional)

If using a local broker, install Mosquitto on your PC:

  • sudo apt install mosquitto mosquitto-clients

Start the broker:

  • mosquitto -v

Test publishing/subscribing:

  • mosquitto_sub -h localhost -t “test/topic”
  • mosquitto_pub -h localhost -t “test/topic” -m “Hello MQTT”

ESP32 MQTT Code:

#include <WiFi.h>

#include <PubSubClient.h>

// WiFi credentials

const char* ssid = “Your_SSID”;

const char* password = “Your_PASSWORD”;

// MQTT Broker details

const char* mqtt_server = “broker.hivemq.com”; // Public broker

const char* mqtt_topic = “home/sensor/temp”;

// ESP32 WiFi and MQTT Client

WiFiClient espClient;

PubSubClient client(espClient);

void setup_wifi() {

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    Serial.print(“.”);

  }

  Serial.println(“Connected to WiFi”);

}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print(“Message received on topic: “);

  Serial.println(topic);

  Serial.print(“Message: “);

  for (int i = 0; i < length; i++) {

    Serial.print((char)payload[i]);

  }

  Serial.println();

}

void reconnect() {

  while (!client.connected()) {

    Serial.print(“Attempting MQTT connection…”);

    if (client.connect(“ESP32Client”)) {

      Serial.println(“Connected!”);

      client.subscribe(mqtt_topic);

    } else {

      Serial.print(“Failed, rc=”);

      Serial.print(client.state());

      Serial.println(” retrying in 5 seconds…”);

      delay(5000);

    }

  }

}

void setup() {

  Serial.begin(115200);

  setup_wifi();

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);

}

void loop() {

  if (!client.connected()) {

    reconnect();

  }

  client.loop();

   

  // Publish test data every 5 seconds

  static unsigned long lastMsg = 0;

  if (millis() – lastMsg > 5000) {

    lastMsg = millis();

    float temperature = 25.5; // Example data

    char tempString[8];

    dtostrf(temperature, 1, 2, tempString);

    client.publish(mqtt_topic, tempString);

    Serial.println(“Data Published: ” + String(tempString));

  }

}

MQTT Over Secure Connection (TLS)

For secure communication, use MQTT over TLS (port 8883). You need the broker’s certificate and fingerprint.

  • WiFiClientSecure espClient;
  • PubSubClient client(espClient);

Set TLS connection:

  • espClient.setCACert(mqtt_broker_cert);
  • client.setServer(mqtt_server, 8883);

ESP32 MQTT with Blynk, Node-RED, or ThingsBoard

  1. Blynk + MQTT – Control ESP32 remotely using Blynk.
  2. Node-RED + MQTT – Build dashboards for real-time IoT monitoring.
  3. ThingsBoard + MQTT – Cloud-based monitoring with visualization.

Use cases of ESP32 MQTT:

  • Home Automation – Control lights, fans, and appliances via MQTT.
  • Remote Sensor Monitoring – Send temperature/humidity data to cloud platforms.
  • Industrial IoT – Monitor machines and send alerts in real-time.
  • Drone/Robot Control – Send commands to ESP32-based drones or robots

Leave a comment

Your email address will not be published. Required fields are marked *