ESP32 Arduino MQTT Client Example - PubSubClient Library

This tutorial will show you How to Communicate with MQTT broker, Publish and Subscribe of different topics. We will use Arduino IDE 2.0 and PubSubClient MQTT Client Library.

ESP32 MQTT Communication.

What is MQTT?

MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe based messaging protocol designed for resource-constrained devices and low-bandwidth, high-latency, or unreliable networks. It is widely used in Internet of Things (IoT) applications, providing efficient communication between sensors, actuators, and other devices.

Key Features of MQTT
  • Lightweight
    Requires fewer resources and has small overhead.
  • Reliable
    Has low latency and supports QOS levels which ensures reliable message delivery.
  • Secure Communications
    Supports TLS, SSL encryption and ensures data confidentiality during transmission.
  • Bi-directionality
    Allows bi-directional communication between devices. Client devices can publish and subscribe to receive messages based on topics.
  • Large-scale IoT device support
    Lightweight nature, low bandwidth consumption and efficient resource use.
  • Language support
    Has broad language support which enables easy integration with multiple platforms.



MQTT Client Library for Arduino IDE

There are many MQTT client libraries available with different features and drawbacks. Below two are widely used MQTT Client libraries.

List of Libraries,

  • PubSubClient
  • ArduinoMqttClient

PubSubClient

A lightweight and long established library, suitable for memory constrained devices. It is compatible with wide range of hardware devices.

Benefits of PubSubClient

  • Has minimal footprint.
  • Vast support in community.
  • Wide availability of examples.
  •  Compatibility with numerous boards.

ArduinoMqttClient

A modern library developed by Arduino team, it is designed to be compatible with all Arduino Architectures and is maintained actively.

Benefits of ArduinoMqttClient

  • Has official support.
  • Modern library.
  • Based on eclipse paho project.
  • Compatibility with all Arduino architectures.
In this tutorial we will use PubSubClient Library.



Prerequisite

Before proceeding further make sure you have installed Arduino IDE with ESP32 Boards. You can follow steps mentioned at this link to install and configure Arduino IDE.
Install Arduino IDE


Install PubSubClient Library on Arduino IDE 2.0
Install PubSubClient library which we will use in this tutorial following below mentioned steps,
  1. Open Arduino IDE and Click on Library Manager tab on left side,

    Library Manager on Arduino IDE 2.0

  2. Search "PubSubClient" in Library Manager,
    Click on Install button for PubSubClient library listed in Library Manager.

    Install PubSubClient on Arduino IDE 2.0 using Library Manager


Hardware Used

In this tutorial we are using ESP32-C6 Dev Kit. You can use any ESP32 based board with this code.

ESP32-C3-DevKitC-02 is an entry-level development board based on ESP32-C3-WROOM-02 or ESP32-C3-WROOM-02U, general-purpose modules with 4 MB SPI flash. This board integrates complete Wi-Fi and Bluetooth® Low Energy functions.



Code


/*
MQTT Client Example using PubSubClient Library. For More details visit : https://www.embetronics.com/ */ /* Header Files */ #include <WiFi.h> #include <PubSubClient.h> /* WiFi Credentials */ const char *ssid = "WIFINAME"; const char *password = "PASSWORD"; /* MQTT Broker Details */ const char *mqtt_broker = "test.mosquitto.org"; const char *topic = "EmbeTronics/client"; const int mqtt_port = 1883; /* Clinet Nodes for WiFi and MQTT Library */ WiFiClient espClient; PubSubClient client(espClient); /* Callback function for MQTT Client */ void callback(char *topic, byte *payload, unsigned int length) { Serial.println("-----------------------"); Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); Serial.println("-----------------------"); } void setup() { /* UART Init */ Serial.begin(115200); /* WiFi Conenction */ WiFi.begin(ssid, password); Serial.print("\r\nConnecting to WiFi.."); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.println("\r\nConnected to the WiFi network"); /* Connect with MQTT Broker */ client.setServer(mqtt_broker, mqtt_port); client.setCallback(callback); while (!client.connected()) { String client_id = "esp32-client-"; client_id += String(WiFi.macAddress()); Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str()); if (client.connect(client_id.c_str())) { Serial.println("mqtt broker connected"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } } client.publish(topic, "Hello from EmbeTronics!!"); /* SubScribe */ client.subscribe(topic); } void loop() { client.loop(); }


Working of Code

Lets see how code works using below mentioned steps, 
  1. For connecting with MQTT broker, We will use online MQTT client from HIVEMQ,
    https://www.hivemq.com/demos/websocket-client/
  2. Enter details like Host, Port and Click on Connect button,

    Online HiveMQ MQTT Client.

  3. Lets Subscribe to "EmbeTronics/client" topic,
    Click on "Add New Topic Subscription" button on right side and enter "EmbeTronics/client" in topic textbox. Click on "Subsribre" button to subscribe.

    HiveMQTT Client Subscribe Topic.

  4. Now, Lets upload Program using Arduino IDE 2.0 and Open Serial Monitor, You can see below logs.

    ESP-ROM:esp32c3-api1-20210207
    Build:Feb  7 2021
    rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT)
    SPIWP:0xee
    mode:DIO, clock div:1
    load:0x3fcd5820,len:0x1174
    load:0x403cbf10,len:0xb54
    load:0x403ce710,len:0x2fb4
    entry 0x403cbf10
    
    Connecting to WiFi..............
    Connected to the WiFi network
    The client esp32-client-68:67:25:4E:9A:4C connects to the public mqtt broker
    mqtt broker connected
    -----------------------
    Message arrived in topic: EmbeTronics/client
    Message:Hi from MQTT broker!!
    -----------------------
    Current date and time: 2025-11-23 18:39:59


  5. When Code starts executing on ESP32 device, It will publish message "Hello from Embetronics!!"
  6. You can publish message from HiveMQ Online MQTT Client, Received message will be printed on Serial Monitor as below,

    -----------------------
    Message arrived in topic: EmbeTronics/client
    Message:Hi from MQTT broker!!
    -----------------------



Video





Wrapping Up

In todays tutorial you have learned how to use MQTT protocol with PubSubClient Client library with Arduino IDE 2.0. MQTT protocol can be used with other devices, too.

Please leave a comment if you have a question or you found this helpful.


Tags

esp32 arduino mqtt client,
ESP32 MQTT broker,
Esp32 arduino mqtt client tutorial,
ESP32 MQTT library,
ESP32 MQTT publish example,
ESP32 PubSubClient example

Post a Comment

0 Comments