In this Project we will explain how to setup the MQTT protocol on ESP8266 and show in an example how communication between ESP8266 and a MQTT broker works .

The objective of this post is to explain how to connect the ESP8266 to a MQTT broker. If you are not familiar with the protocol, you can read more about below. Although this example should work fine with other brokers, we will assume that the broker will be hosted on CloudMQTT. Since CloudMQTT has a free plan, we can just create an account and test it. Setting an account is really simple and it’s outside the scope of this post. You can check here how to do it and how to create a broker instance.

 

About MQTT

MQTT is a simple messaging protocol, designed for constrained devices with low-bandwidth. So, it’s the perfect solution for Internet of Things applications. MQTT allows you to send commands to control outputs, read and publish data from sensor nodes and much more.

The first concept is the publish and subscribe system. In a publish and subscribe system, a device can publish a message on a topic, or it can be subscribed to a particular topic to receive messages.

  • For example Device 1 publishes on a topic.
  • Device 2 is subscribed to the same topic as device 1 is publishing in.
  • So, device 2 receives the message.

MQTT – Messages

Messages are the information that you want to exchange between your devices. Whether it’s a command or data.

MQTT – Topics

Another important concept are the topics. Topics are the way you register interest for incoming messages or how you specify where you want to publish the message.

Topics are represented with strings separated by a forward slash. Each forward slash indicates a topic level. Here’s an example on how you would create a topic for a temperature in your kitchen of your home:


Note:
topics are case-sensitive

If you would like to log room temperatures in your home kitchen using MQTT you can imagine the following scenario:

  1. You have a device (ESP8266) that publishes messages containing room temperatures on the Home/Kitchen/temperature topic.
  2. You have a device (PC, mobile phone) that is subscribed to that topic: Home/Kitchen/temperature.
  3. So, when a new message is published on that topic, the device that subscribed to that topic gets the latest temperature reading.

 

MQTT – Broker

At last, you also need to be aware of the term broker.

The broker is primarily responsible for receiving all messages, filtering the messages, decide who is interested in them and then publishing the message to all subscribed clients. There are several brokers you can use. In some of our home automation projects we use the Mosquitto broker which can be installed in the Raspberry Pi. Alternatively, you can use a cloud MQTT broker. In this example we will use CloudMQTT MQTT broker.

The Overall Architecture

In this example we will have one ESP8266 connected to a DHT22 temperature sensor. This devices has the role of a publisher within the MQTT architecture. Temperature will be measured every 10 seconds and published in the Home/Kitchen/temperature. A subscriber that has subscribed to this topic, in this case a computer or another ESP8266, will receive and display the latest temperature log from the ESP8266 .

 

Image: Architecture of publishers and subscribers with ESP8266 and MQTT Broker

Materials Needed

For the sake of simplicity, this project is demonstrated in its most basic form in such that features and materials are kept at a minimum.  Following materials are needed for this project:

  1. DHT22 Temperature Sensor
  2. NodeMCU ESP8266
  3. Wifi router
  4. Smartphone or PC with Web Browser and Wifi capability

 

MQTT Broker

Although this example should work fine with other brokers, we will assume that the broker will be hosted on CloudMQTT. Since CloudMQTT has a free plan, we can just create an account and test it. Setting an account is really simple and it’s outside the scope of this post. You can check here how to do it and how to create a broker instance. Here is a list of other MQTT brokers that are available with free plans for MQTT applications.

 

 

 

ESP8266 Code (Subscriber)

First, we start by including the libraries needed for all the functionality. We need the ESP8266WiFi library, in order to be able to connect the ESP8266 to a WiFi network, and the PubSubClient library, which allows us to connect to a MQTT broker and publish/subscribe messages in topics. The PubSubClient library can be installed via Arduino IDE library manager. The coding shown here is based on the examples provided in the library, which I encourage you to try.

#include <esp8266wifi.h>
#include <pubsubclient.h>

We will also need the information and credentials of the MQTT server. As explained in the introduction, you will need to know the server address, the port, the username and the password. Use your values in the variables bellow.

 
const char* mqttServer = "m11.cloudmqtt.com";

//edit this information below according to the  CloudMQTT instance information
const int mqttPort = 12345;      
const char* mqttUser = "MQTTuser";
const char* mqttPassword = "MQTTuserPasswprd";

We will subscribe to topic "Home/Kitchen/temperature", so we can receive messages from other publishers. To do so, we call the subscribe method, passing as input the name of the topic.

client.subscribe("Home/Kitchen/temperature");

After the initialization, we need to specify the callback function, which will handle the incoming messages for the topics subscribed. The arguments of this function are the name of the topic, the payload (in bytes) and the length of the message. It should return void. In this function, we will first print the topic name to the serial port, and then print each byte of the message received. Since we also have the length of the message as argument of the function, this can be easily done in a loop.

void callback(char* topic, byte* payload, unsigned int length) {
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("-----------------------");
}

The full code for the ESP8266 MQTT subscriber is below:

#include 
#include 
const char* ssid = "YourNetworkName";
const char* password =  "YourNetworkPassword";

//edit this information below according to the  CloudMQTT instance information
const char* mqttServer = "m11.cloudmqtt.com";
const int mqttPort = 12948;
const char* mqttUser = "MQTTuser";
const char* mqttPassword = "MQTTuserPassword";

WiFiClient espClient;
PubSubClient client(espClient);


void setup() {
 
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
 
      Serial.println("connected");  
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.subscribe("Home/Kitchen/temperature");
 
}

void loop() {
  client.loop();
}



void callback(char* topic, byte* payload, unsigned int length) {
 
  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("-----------------------");
 
}

ESP8266 Code (Publisher)

The publisher ESP8266 will measure the room temperature every 10 sec and publish it in topic "Home/Kitchen/temperature". Again, we need the ESP8266WiFi library, and the PubSubClient library. Furthermore, the publisher measures temperatures via the DHT22 digital temperature and humidity sensor. Thus we need to include the DHTesp library, which canbe found via the Arduino IDE's library manager under "DHT sensor library for ESPx".

#include <esp8266wifi.h>
#include <pubsubclient.h>
#include "DHTesp.h"
DHTesp dht;
String temperature;

const char* ssid = "YourNetworkName";
const char* password = "YourNetworkPassword";

//edit this information below according to the CloudMQTT instance information
const char* mqttServer = "m11.cloudmqtt.com";
const int mqttPort = 12948;
const char* mqttUser = "MQTTuser";
const char* mqttPassword = "MQTTuserPassword";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

Serial.begin(115200);

WiFi.begin(ssid, password);
dht.setup(D1, DHTesp::DHT22); //temperature sensor is connected to Pin D1 of the ESP8266
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");

client.setServer(mqttServer, mqttPort);
//client.setCallback(callback);

while (!client.connected()) {
Serial.println("Connecting to MQTT...");

if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {

Serial.println("connected");

} else {

Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);

}
}

}

void loop() {
temperature =(String) dht.getTemperature();
Serial.print("Measured Temp: "); 
Serial.println(temperature);
Serial.print("°C");
client.publish("Home/Kitchen/temperature", temperature);
Serial.print("Published to Home/Kitchen/temperature");
client.loop();
delay(5000);
delay(5000);
}

 

Test the Setup

After making sure the MQTT server is running, we need to test the code. To do so, we just upload it and run it on the ESP8266. Then, we open the Arduino IDE serial console, so the output gets printed.

Upon running, the publisher ESP8266 will measure the temperature and publish it, which will be also printed on the serial. After that, the ESP8266 subscriber that subcribed to the same topic to which the temperature message was sent will print the temperature via serial.

If any other producer sends a message to the “Home/Kitchen/temperature” topic, then it will be printed in the serial console, as shown below.
 
 

MQTT publisher ESP8266 serial output

MQTT subscriber ESP8266 serial output

For testing the MQTT communication in this tutorial, we use MQTTlens, a Google Chrome application, which connects to a MQTT broker and is able to subscribe and publish to MQTT topics . This is a very useful application that this type of tests.

For the test, MQTTlens is subscribing or publishing to the “Home/Kitchen/temperature” topic before connecting the ESP8266. So, it is possible to have a virtual dummy subscriber or publisher to see if the MQTT server is processing messages in the first place.

Wrap-Up

MQTT is a communication protocol based on a publish and subscribe system. It is simple to use and it is great for Internet of Things and Home Automation projects.
We have learned about the MQTT protocol and its subscriber - publisher relationship. Furthermore, we are now able to configure a free MQTT server, and program the ESP8266 in order to communicate with the MQTT server in both subscriber and publisher roles. We hope you’ve found this tutorial useful and you now understand what is MQTT and how it works.

(Visited 103 times, 7 visits today)