ESPHow ToIoT HardwaresTutorials/DIY

How to Connect ESP32 to MQTT Broker Using CloudMQTT

In this tutorial we learn How to connect ESP32 to MQTT broker using CloudMQTT. CloudMQTT is a popular MQTT broker. You can use this platform easily.

We know that there are many cloud platforms and protocols available but MQTT is one of the most used IoT protocol for Iot projects. Now we are establishing connection between MQTT server and ESP32 board using CloudMQTT.

ESP32 is a Successor of popular ESP8266 Wi-Fi module, with many advanced features. if you want know more about ESP32, please visit this link ESP32 Tutorials | ESP32 BLE | ESP32 add-on Arduino IDE | How To Use

While, MQTT used to stand for Message Queuing Telemetry Transport, but is today referred to simply as MQTT and is no longer an acronym. It is an extremely simple and lightweight Publish/Subscribe messaging protocol invented at IBM and Arcom (now Eurotech) to connect restricted devices in low bandwidth, high-latency or unreliable networks.

Visit this for more information : MQTT | What is MQTT | MQTT in Depth | QoS | FAQs | MQTT Introduction

What is MQTT Client & Broker? 

MQTT Client: An MQTT client runs a MQTT library and connects to an MQTT broker over a network. Both publisher and subscriber are MQTT clients. The publisher and subscriber refer that whether the client is publishing messages or subscribing to messages.

MQTT Broker: The broker receives all messages, filter the messages, determine who is subscribed to each message, and send the message to these subscribed clients.

Recommended: MQTT Servers/BrokersMQTT Public Brokers List

How to Connect ESP32 to MQTT Broker Using CloudMQTT

We need an ESP32 board and Arduino IDE with some libraries. if you don’t know how to use esp32 with arduino IDE please visit this link ESP32 Tutorials | ESP32 BLE | ESP32 add-on Arduino IDE | How To Use.

Cloud MQTT Account Setup

Visit www.cloudmqtt.com and sign up using you email.

After login, click on + Create New Instance to create a new instance.

Now enter your instance name and select Cute Cat’ in plan option.

In new tab select region and click on ‘Review’.

Your instance is created and you can view your details like user and password.

ESP32 MQTT Broker Code

The complete code for Connecting ESP32 with MQTT broker is given at the end. Here, we are using Arduino IDE to program ESP32. First, install WiFi.h library and PubSubClient library.

PubSubClient library allows us to publish/subscribe messages in topics.

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

now we declare few global variables for our WiFi and MQTT connections. Enter your WiFi and MQTT details in below variables:

const char* ssid = "iotbyhvm.ooo"; // Enter your WiFi name
const char* password =  "iotbyhvm"; // Enter WiFi password
const char* mqttServer = "m16.cloudmqtt.com"; // enter mqtt server 
const int mqttPort = 12595; //enter mqtt port
const char* mqttUser = "username";  //enter mqtt user
const char* mqttPassword = "password"; // enter mqtt password

In the setup_wifi function, it will check the WiFi, whether it is connected to network or not, also give the IP address and print it on the serial monitor.

void setup_wifi() {
    delay(10);
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

In the below, while loop function, it will connect to the MQTT server and will print it on the serial monitor. This process will run in a loop until it gets connected.

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("enter topic name", "hello world");
      // ... and resubscribe
      client.subscribe(MQTT_SERIAL_RECEIVER_CH);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);

Now we will specify a call back function and in this function, we will first print the topic name and then received message.

void callback(char* topic, byte *payload, unsigned int length) {
    Serial.println("-------new message from broker-----");
    Serial.print("channel:");
    Serial.println(topic);
    Serial.print("data:"); 
    Serial.write(payload, length);
    Serial.println();
}

Testing MQTT with ESP32

Upload this code into ESP32 using Arduino IDE and open the serial monitor. here you can find connection status and IP address.

To subscribe and publish to MQTT topics, a Google Chrome application MQTTlens will be used. You can download the app from here.

Launch this app and set up a connection with MQTT broker. To setup, connection click on ‘connections’ and in next window enter your connection details from Cloud MQTT account.

Save this connection, and  now you can subscribe and publish a message on your MQTT broker.

To subscribe or publish a message enter your topic name in subscribe and publish option and enter the default message.

Your message will be shown on serial monitor.

Complete Code

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

// Update these with values suitable for your network.
const char* ssid = "iotbyhvm.ooo";
const char* password = "iotbyhvm";
const char* mqtt_server = "m16.cloudmqtt.com";
#define mqtt_port 12595
#define MQTT_USER "enter username"
#define MQTT_PASSWORD "enter password"
#define MQTT_SERIAL_PUBLISH_CH "/enter topic"
#define MQTT_SERIAL_RECEIVER_CH "/enter topic"

WiFiClient wifiClient;

PubSubClient client(wifiClient);

void setup_wifi() {
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("/enter topic name/", "hello world");
      // ... and resubscribe
      client.subscribe(MQTT_SERIAL_RECEIVER_CH);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte *payload, unsigned int length) {
    Serial.println("-------new message from broker-----");
    Serial.print("channel:");
    Serial.println(topic);
    Serial.print("data:");  
    Serial.write(payload, length);
    Serial.println();
}

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(500);// Set time out for 
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  reconnect();
}

void publishSerialData(char *serialData){
  if (!client.connected()) {
    reconnect();
  }
  client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
}
void loop() {
   client.loop();
   if (Serial.available() > 0) {
     char mun[501];
     memset(mun,0, 501);
     Serial.readBytesUntil( '\n',mun,500);
     publishSerialData(mun);
   }
 }

I hope you like this post. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

One thought on “How to Connect ESP32 to MQTT Broker Using CloudMQTT

  • It was a long time ago since I used the online Arduino IDE, but when I tried to compile the code it failed on:
    “/home/builder/opt/libraries/latest/wifinina_1_5_0/src/utility/spi_drv.cpp:87:24: error: ‘PINS_COUNT’ was not declared in this scope

    if (SLAVERESET > PINS_COUNT) { ”
    It looks like in the external libraries.
    On top of it, it looks like they started to charge for ESP8266 support boards.

    I will try to compile on other platforms.
    Can you comment on that?

    Reply

Leave a Reply

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