0
0
Drone-programmingHow-ToBeginner · 4 min read

How to Use MQTT with ESP32: Simple Guide and Example

To use MQTT with ESP32, install the PubSubClient library in Arduino IDE, connect ESP32 to Wi-Fi, then connect to an MQTT broker using the library's client. Publish and subscribe to topics to send and receive messages easily.
📐

Syntax

The basic steps to use MQTT with ESP32 are:

  • Include libraries: WiFi.h for Wi-Fi and PubSubClient.h for MQTT.
  • Setup Wi-Fi: Connect ESP32 to your Wi-Fi network.
  • Setup MQTT client: Define broker address and port, then connect.
  • Publish/Subscribe: Use publish() to send messages and subscribe() to listen to topics.
cpp
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "yourSSID";
const char* password = "yourPASSWORD";
const char* mqtt_server = "broker.hivemq.com";

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("ESP32Client")) {
      client.subscribe("test/topic");
    } else {
      delay(5000);
    }
  }
}

void setup() {
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("test/topic", "Hello from ESP32");
  delay(2000);
}
💻

Example

This example connects ESP32 to Wi-Fi and an MQTT broker, subscribes to a topic, and publishes a message every 2 seconds.

cpp
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "yourSSID";
const char* password = "yourPASSWORD";
const char* mqtt_server = "broker.hivemq.com";

WiFiClient espClient;
PubSubClient client(espClient);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("]: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void setup_wifi() {
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("ESP32Client")) {
      client.subscribe("test/topic");
    } else {
      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();
  client.publish("test/topic", "Hello from ESP32");
  delay(2000);
}
Output
Message arrived [test/topic]: Hello from ESP32 Message arrived [test/topic]: Hello from ESP32 ...
⚠️

Common Pitfalls

  • Wrong Wi-Fi credentials: ESP32 won't connect if SSID or password is incorrect.
  • MQTT broker unreachable: Check broker address and port.
  • Not calling client.loop() regularly: This stops MQTT communication.
  • Using delay() excessively: Can block MQTT client; use short delays or timers.
cpp
// Wrong way:
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  // Missing client.loop() call
  delay(2000);
}

// Right way:
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(2000);
}
📊

Quick Reference

Remember these key points when using MQTT with ESP32:

  • Use PubSubClient library for MQTT functions.
  • Always connect ESP32 to Wi-Fi before MQTT.
  • Call client.loop() frequently in loop().
  • Use client.publish(topic, message) to send messages.
  • Use client.subscribe(topic) to receive messages.

Key Takeaways

Install and use the PubSubClient library to handle MQTT on ESP32.
Connect ESP32 to Wi-Fi before connecting to the MQTT broker.
Always call client.loop() regularly to maintain MQTT connection.
Use publish() to send and subscribe() to receive MQTT messages.
Check Wi-Fi and broker details carefully to avoid connection issues.