How to Connect ESP32 to MQTT Broker

How to Connect ESP32 to MQTT Broker

IoT is a system that connects with the devices that are accessible through the internet. There are number of cloud platforms and protocols, MQTT is one of the most used IoT protocol for IoT projects. In our previous tutorial, we have connected MQTT with Raspberry Pi and ESP8266. Now, we are establishing connection between MQTT server and ESP32.

ESP32 is a Successor of popular ESP8266 Wi-Fi module, with many advanced features such as this module is a dual core 32-bit CPU with built-in Wi-Fi and dual-mode Bluetooth with sufficient amount of 30 I/O pins.

While, MQTT stands for Message Queuing Telemetry Transport, it’s a system where we can publish and subscribe messages as a client. By using MQTT you can send commands to control outputs, read and publish data from sensors and much more. There are two main terms in MQTT i.e. Client and Broker.

 

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.

 

Now, in this tutorial we will explain how to connect to a MQTT broker and subscribe to a topic using ESP32 and Arduino IDE libraries.

 

Components Required

  • ESP32
  • Cloud MQTT

 

Cloud MQTT Account Setup

To set up an account on Cloud MQTT navigate to its official website (www.cloudmqtt.com) and sign up using your email.

MQTT Account Setup for ESP8266

 

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

Create New Instance on MQTT Account for ESP8266

 

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

Select Plan for MQTT Account

 

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

Review MQTT Account Setup for ESP8266

 

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

Login to MQTT Account for ESP8266

 

ESP32 MQTT Broker Code Explanation

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 declare some global variables for our WiFi and MQTT connections. Enter your WiFi and MQTT details in below variables:

const char* ssid = "CircuitLoop"; // Enter your WiFi name
const char* password =  "circuitdigest101"; // Enter WiFi password
const char* mqttServer = "m16.cloudmqtt.com";
const int mqttPort = 12595;
const char* mqttUser = "eapcfltj";
const char* mqttPassword = "3EjMIy89qzVn";

 

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("/icircuit/presence/ESP32/", "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

Now to test the code upload this code into ESP32 using Arduino IDE and open the serial monitor.

Connecting ESP32 to Wifi for MQTT Broker

 

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.

Launch MQTTlens for Connecting with ESP8266

 

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

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

Setup Account on MQTTlens

 

Your message will be shown on serial monitor as shown in the above image of the serial monitor.

Testing MQTT Broker with ESP32

 

Hence, we have successfully connected the MQTT broker with ESP32. Stay Tuned with us for more amazing IoT projects.

Code

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


// Update these with values suitable for your network.
const char* ssid = "CircuitLoop";
const char* password = "circuitdigest101";
const char* mqtt_server = "m16.cloudmqtt.com";
#define mqtt_port 12595
#define MQTT_USER "eapcfltj"
#define MQTT_PASSWORD "3EjMIy89qzVn"
#define MQTT_SERIAL_PUBLISH_CH "/icircuit/ESP32/serialdata/tx"
#define MQTT_SERIAL_RECEIVER_CH "/icircuit/ESP32/serialdata/rx"

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("/icircuit/presence/ESP32/", "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);
   }
 }