ESP32 MQTT Publisher and Subscriber Using PubSubClient

ESP32 MQTT Publisher and Subscriber Using PubSubClient

ESP32 MQTT Publisher and Subscriber Using PubSubClient

The ESP32 is one of the most popular microcontrollers for IoT projects because it combines powerful processing capabilities with built-in Wi-Fi and Bluetooth connectivity. When paired with MQTT, the ESP32 becomes an excellent platform for building smart home systems, environmental monitoring solutions, industrial automation projects, and cloud-connected devices.

In the previous tutorials, we learned what MQTT is and how to set up a Mosquitto MQTT broker on a Raspberry Pi. Now it’s time to connect an ESP32 to that broker and start exchanging data.

In this tutorial, you’ll learn how to configure an ESP32 as both an MQTT Publisher and an MQTT Subscriber using the PubSubClient library. By the end of this guide, your ESP32 will be able to send sensor data to an MQTT broker and receive commands from subscribed topics.

What You Will Build

In this project:

  • ESP32 connects to Wi-Fi
  • ESP32 connects to Mosquitto MQTT Broker
  • ESP32 publishes temperature data
  • ESP32 subscribes to a control topic
  • ESP32 receives messages from MQTT clients
  • MQTT communication is verified using Mosquitto tools

How MQTT Communication Works

ESP32 MQTT Publisher and Subscriber Using PubSubClient

The communication flow is simple:

  1. ESP32 connects to Wi-Fi.
  2. ESP32 connects to the MQTT broker.
  3. ESP32 publishes data to a topic.
  4. MQTT broker receives the message.
  5. Subscribers receive the published data.
  6. ESP32 can also subscribe to topics and receive commands.

This publish-subscribe architecture makes MQTT highly scalable and efficient for IoT applications.

Prerequisites

Before proceeding, ensure you have:

  • ESP32 development board
  • Arduino IDE installed
  • Mosquitto MQTT Broker running
  • Wi-Fi network
  • USB cable

You should also complete:

Install Required Libraries

Open Arduino IDE.

Navigate to:

Sketch → Include Library → Manage Libraries

Search for:

PubSubClient

Install:

PubSubClient by Nick O'Leary

This library simplifies MQTT communication on ESP32 devices.

MQTT Broker Information

For this tutorial:

Broker IP: 192.168.1.150
Port: 1883

Replace the broker IP with your Raspberry Pi MQTT broker address.

ESP32 MQTT Publisher Example

The following example publishes temperature values every five seconds.

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

const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";

const char* mqtt_server = "192.168.1.150";

WiFiClient espClient;
PubSubClient client(espClient);

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")) {
      break;
    }

    delay(5000);
  }
}

void setup() {

  Serial.begin(115200);

  setup_wifi();

  client.setServer(mqtt_server, 1883);
}

void loop() {

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

  client.loop();

  client.publish(
      "home/temperature",
      "25.6");

  delay(5000);
}

Upload the code to your ESP32.

Verify Published Messages

On your Raspberry Pi, subscribe to the topic:

mosquitto_sub -h localhost -t home/temperature

Expected output:

25.6
25.6
25.6

The ESP32 is now publishing MQTT messages successfully.

ESP32 MQTT Subscriber Example

Now let’s make the ESP32 receive MQTT messages.

Add the callback function:

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

  Serial.print("Message received: ");

  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  Serial.println();
}

Inside setup():

client.setCallback(callback);

After connecting:

client.subscribe("home/control");

Upload the updated sketch.

Test MQTT Subscription

Open a terminal on your Raspberry Pi.

Publish a test message:

mosquitto_pub \
-h localhost \
-t home/control \
-m "LED ON"

Serial Monitor output:

Message received: LED ON

The ESP32 has successfully subscribed to the MQTT topic.

MQTT Topics Used in This Tutorial

Publisher Topic

home/temperature

Used for sending sensor data.

Subscriber Topic

home/control

Used for receiving commands.

Organizing topics properly is important as your IoT system grows.

Real-World Applications

This publish-subscribe model is used in many IoT systems.

ESP32 MQTT Publisher and Subscriber Using PubSubClient

Smart Home Automation

  • Light control
  • Fan control
  • Smart switches

Environmental Monitoring

  • Temperature monitoring
  • Humidity monitoring
  • Air quality systems

Industrial IoT

  • Machine monitoring
  • Predictive maintenance
  • Equipment status tracking

Agriculture

  • Soil moisture monitoring
  • Irrigation control
  • Weather stations

Common Issues and Troubleshooting

ESP32 Cannot Connect to Wi-Fi

Verify:

  • SSID is correct
  • Password is correct
  • Router is operational

ESP32 Cannot Connect to MQTT Broker

Verify:

  • Broker IP address
  • Port 1883
  • Mosquitto service status

Check broker status:

sudo systemctl status mosquitto

Messages Not Received

Verify:

  • Publisher topic
  • Subscriber topic
  • Topic spelling

MQTT topics are case-sensitive.

Testing the Complete Flow

A typical communication flow should look like:

ESP32
   ↓
MQTT Publish
   ↓
Mosquitto Broker
   ↓
MQTT Subscribe
   ↓
ESP32 / Node-RED / Dashboard

Once this works successfully, you’re ready to build more advanced IoT systems.

Conclusion

In this tutorial, you’ve learned how to connect an ESP32 to an MQTT broker using the PubSubClient library. You configured the ESP32 as both an MQTT Publisher and an MQTT Subscriber, enabling two-way communication between devices and applications.

This publish-subscribe model forms the foundation of many modern IoT systems. Whether you’re building smart homes, industrial monitoring solutions, or cloud-connected devices, MQTT and ESP32 provide a powerful combination for reliable communication.

In the next tutorial, we’ll use Node-RED to visualize MQTT data and build an interactive dashboard.

Frequently Asked Questions

What is PubSubClient?

PubSubClient is a lightweight Arduino library that allows ESP32 and ESP8266 devices to communicate using MQTT.

Can ESP32 act as both Publisher and Subscriber?

Yes. An ESP32 can publish data to MQTT topics while simultaneously subscribing to other topics.

Which MQTT broker should I use with ESP32?

Mosquitto is one of the most popular MQTT brokers for beginners and IoT projects.

Does ESP32 support MQTT over Wi-Fi?

Yes. MQTT communication is commonly used over Wi-Fi with ESP32 devices.

What port does MQTT use?

The default MQTT port is 1883.

Can multiple ESP32 boards connect to one MQTT broker?

Yes. A single MQTT broker can handle many publishers and subscribers simultaneously.

Related MQTT Tutorials:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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