ESP8266 - MQTT

In this tutorial, we will explore how to utilize ESP8266 for sending and receiving data with an MQTT broker using the MQTT protocol. Specifically, we will cover the following:

ESP8266 NodeMCU MQTT

We will delve into two distinct scenarios:

Hardware Preparation

1×ESP8266 NodeMCU
1×Micro USB Cable
1×(Optional) Screw Terminal Expansion Board for ESP8266

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of ESP8266 and MQTT

If you're not yet familiar with the MQTT protocol, you can find information about it online. This tutorial focuses on using ESP8266 for sending and receiving data through MQTT.

Here are some ways ESP8266 can be used with MQTT:

  • You can connect ESP8266 to an online MQTT broker such as Mosquitto or AWS IoT.
  • Alternatively, you can link ESP8266 to an MQTT broker installed on your computer, like Mosquitto or HiveMQ.
  • If you have a Raspberry Pi, ESP8266 can connect to an MQTT broker running on it, for instance, Mosquitto.
  • Additionally, ESP8266 can be connected to a cloud-based MQTT broker, such as Mosquitto or HiveMQ on AWS EC2.

In this tutorial, we'll begin by testing whether ESP8266 can connect to an online Mosquitto broker. We'll demonstrate ESP8266's ability to send and receive data through this broker over the internet.

Next, we'll guide you through setting up the Mosquitto broker on your computer. ESP8266 will then connect to this local broker, allowing you to continue sending and receiving data.

Once you've completed this tutorial, you can delve deeper by exploring these additional tutorials:

These resources will provide further insight into related topics.

Connect ESP8266 to an online MQTT broker

In this part, we will learn how to connect ESP8266 to test.mosquitto.org, an online MQTT broker created by Mosquitto. Please note that this broker should be used for the testing purpose only.

ESP8266 Code

The below ESP8266 code does:

  • Connect to the MQTT broker
  • Subscribe to a topic
  • Periodically publish messages to the same topic that it subscribes
/* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-mqtt */ #include <ESP8266WiFi.h> #include <MQTTClient.h> #include <ArduinoJson.h> const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD const char MQTT_BROKER_ADRRESS[] = "test.mosquitto.org"; // CHANGE TO MQTT BROKER'S ADDRESS const int MQTT_PORT = 1883; const char MQTT_CLIENT_ID[] = "YOUR-NAME-esp8266-001"; // CHANGE IT AS YOU DESIRE const char MQTT_USERNAME[] = ""; // CHANGE IT IF REQUIRED, empty if not required const char MQTT_PASSWORD[] = ""; // CHANGE IT IF REQUIRED, empty if not required // The MQTT topics that ESP8266 should publish/subscribe const char PUBLISH_TOPIC[] = "YOUR-NAME-esp8266-001/loopback"; // CHANGE IT AS YOU DESIRE const char SUBSCRIBE_TOPIC[] = "YOUR-NAME-esp8266-001/loopback"; // CHANGE IT AS YOU DESIRE const int PUBLISH_INTERVAL = 5000; // 5 seconds WiFiClient network; MQTTClient mqtt = MQTTClient(256); unsigned long lastPublishTime = 0; void setup() { Serial.begin(9600); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("ESP8266 - Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); connectToMQTT(); } void loop() { mqtt.loop(); if (millis() - lastPublishTime > PUBLISH_INTERVAL) { sendToMQTT(); lastPublishTime = millis(); } } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); // Create a handler for incoming messages mqtt.onMessage(messageHandler); Serial.print("ESP8266 - Connecting to MQTT broker"); while (!mqtt.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(100); } Serial.println(); if (!mqtt.connected()) { Serial.println("ESP8266 - MQTT broker Timeout!"); return; } // Subscribe to a topic, the incoming messages are processed by messageHandler() function if (mqtt.subscribe(SUBSCRIBE_TOPIC)) Serial.print("ESP8266 - Subscribed to the topic: "); else Serial.print("ESP8266 - Failed to subscribe to the topic: "); Serial.println(SUBSCRIBE_TOPIC); Serial.println("ESP8266 - MQTT broker Connected!"); } void sendToMQTT() { StaticJsonDocument<200> message; message["timestamp"] = millis(); message["data"] = analogRead(0); // Or you can read data from other sensors char messageBuffer[512]; serializeJson(message, messageBuffer); mqtt.publish(PUBLISH_TOPIC, messageBuffer); Serial.println("ESP8266 - sent to MQTT:"); Serial.print("- topic: "); Serial.println(PUBLISH_TOPIC); Serial.print("- payload:"); Serial.println(messageBuffer); } void messageHandler(String &topic, String &payload) { Serial.println("ESP8266 - received from MQTT:"); Serial.println("- topic: " + topic); Serial.println("- payload:"); Serial.println(payload); }

Detailed Instructions

To get started with ESP8266 on Arduino IDE, follow these steps:

  • Check out the how to setup environment for ESP8266 on Arduino IDE tutorial if this is your first time using ESP8266.
  • Connect the ESP8266 board to your computer using a USB cable.
  • Open Arduino IDE on your computer.
  • Choose the correct ESP8266 board, such as (e.g. NodeMCU 1.0 (ESP-12E Module)), and its respective COM port.
  • Open the Library Manager by clicking on the Library Manager icon on the left navigation bar of Arduino IDE
  • Type MQTT on the search box, then look for the MQTT library by Joel Gaehwiler.
  • Click Install button to install MQTT library.
ESP8266 NodeMCU MQTT library
  • Type ArduinoJson on the search box, then look for the ArduinoJson library by Benoit Blanchon.
  • Click Install button to install ArduinoJson library.
ESP8266 NodeMCU Json library
  • Copy the above code and open with Arduino IDE
  • Replace the WiFi information (SSID and password) in the code with your own.
  • In the code, you will see the word 'YOUR-NAME' three times. Replace this word with your name or random characters (alphabet characters only, no spaces). This is necessary because if you do not make the change, there may be multiple people running this code at the same time, which could lead to conflicts because the MQTT client IDs and topics are the same for everyone.
  • Click Upload button on Arduino IDE to upload code to ESP8266
  • Open the Serial Monitor
  • See the result on Serial Monitor.
COM6
Send
ESP8266 - Connecting to MQTT broker ESP8266 - Subscribed to the topic: YOUR-NAME-esp8266-001/loopback ESP8266 - MQTT broker Connected! ESP8266 - sent to MQTT: - topic: YOUR-NAME-esp8266-001/loopback - payload:{"timestamp":11757,"data":255} ESP8266 - received from MQTT: - topic: YOUR-NAME-esp8266-001/loopback - payload: {"timestamp":11757,"data":255} ESP8266 - sent to MQTT: - topic: YOUR-NAME-esp8266-001/loopback - payload:{"timestamp":16896,"data":259} ESP8266 - received from MQTT: - topic: YOUR-NAME-esp8266-001/loopback - payload: {"timestamp":16896,"data":259}
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

As you can see, ESP8266 publishes messages to the MQTT broker, then receives back the same message. That is because the above code subscribes to the same topic that it publishes data to. If you do not want ESP8266 to receive the message that it publishes, simply make the SUBSCRIBE topic different from the PUBLISH topic.

Connect ESP8266 to the MQTT broker installed on your PC

Installing Mosquitto MQTT Broker

  • Install it on the D: drive instead of the C: drive. Avoid installing the Mosquitto broker on the C: drive to prevent potential issues.

Run Mosquitto MQTT broker

Now, let's check if the MQTT broker is functioning properly by following these steps:

  • Go to the directory where Mosquitto was installed. For instance: D:\mqtt\mosquitto>
  • Make a new file named test.conf, copy the content below, and save it in that directory:
listener 1883 allow_anonymous true
  • Run a Command Prompt as Administrator on your PC. Let's call it Broker Window. Do not close it until the end of the tutorial.
Windows command prompt administrator
  • Run the below commands one by one:
cd /d D:\mqtt\mosquitto mosquitto -v -c test.conf
  • You will see:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\mqtt\mosquitto D:\mqtt\mosquitto>mosquitto -v -c test.conf 1710918939: mosquitto version 2.0.18 starting 1710918939: Config loaded from test.conf. 1710918939: Opening ipv6 listen socket on port 1883. 1710918939: Opening ipv4 listen socket on port 1883. 1710918939: mosquitto version 2.0.18 running
  • Open another Command Prompt as Administrator on your PC.
  • Find the IP address of your PC by running the below command:
ipconfig
Command Prompt
C:\WINDOWS\system32>ipconfig Windows IP Configuration Ethernet adapter: Subnet Mask . . . . . . . . . . . : 255.0.0.0 IPv4 Address. . . . . . . . . . . : 192.168.0.26 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . :
  • Write down the IP address for later use. In the above example: 192.168.0.26

Test if the Mosquitto Broker works

  • Open another Command Prompt as Administrator on your PC. Let's call it Subscriber Window
  • Subscribe to a topic by running the below commands one by one (replace by your IP address):
cd /d D:\mqtt\mosquitto mosquitto_sub -h 192.168.0.26 -p 1883 -t esp8266-001/send
  • Open another Command Prompt as Administrator on your PC. Let's call it Publisher Window
  • Publish a message to the same topic by running the below commands one by one (replace by your IP address):
cd /d D:\mqtt\mosquitto mosquitto_pub -h 192.168.0.26 -p 1883 -t esp8266-001/send -m "Hello, MQTT!"
  • You will see:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\mqtt\mosquitto D:\mqtt\mosquitto>mosquitto_pub -h 192.168.0.26 -p 1883 -t esp8266-001/send -m "Hello, MQTT!" D:\mqtt\mosquitto>

You will see that message is forwarded to the Subscriber Window as follows:

Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\mqtt\mosquitto D:\mqtt\mosquitto>mosquitto_sub -h 192.168.0.26 -p 1883 -t esp8266-001/send Hello, MQTT!

Now, you installed successfully the Mosquitto MQTT broker on your PC. Please do NOT close three windows: Broker Window, Subscriber Window, and Publisher Window. We will use them next.

ESP8266 Code

The below ESP8266 code does:

  • Connect to the MQTT broker
  • Subscribe to a topic
  • Periodically publish messages to another topic
/* * This ESP8266 NodeMCU code was developed by newbiely.com * * This ESP8266 NodeMCU code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp8266/esp8266-mqtt */ #include <ESP8266WiFi.h> #include <MQTTClient.h> #include <ArduinoJson.h> #define CLIENT_ID "ESP8266-001" // CHANGE IT AS YOU DESIRE const char WIFI_SSID[] = "YOUR_WIFI_SSID"; // CHANGE TO YOUR WIFI SSID const char WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD"; // CHANGE TO YOUR WIFI PASSWORD const char MQTT_BROKER_ADRRESS[] = "192.168.0.26"; // CHANGE TO MQTT BROKER'S IP ADDRESS const int MQTT_PORT = 1883; const char MQTT_USERNAME[] = ""; // CHANGE IT IF REQUIRED const char MQTT_PASSWORD[] = ""; // CHANGE IT IF REQUIRED // The MQTT topics that this device should publish/subscribe #define PUBLISH_TOPIC "esp8266-001/send" #define SUBSCRIBE_TOPIC "esp8266-001/receive" #define PUBLISH_INTERVAL 5000 // 4 seconds WiFiClient network; MQTTClient mqtt = MQTTClient(256); unsigned long lastPublishTime = 0; void setup() { Serial.begin(9600); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.println("ESP8266 - Connecting to Wi-Fi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to WiFi network with IP Address: "); Serial.println(WiFi.localIP()); connectToMQTT(); } void loop() { mqtt.loop(); if (millis() - lastPublishTime > PUBLISH_INTERVAL) { sendToMQTT(); lastPublishTime = millis(); } } void connectToMQTT() { // Connect to the MQTT broker mqtt.begin(MQTT_BROKER_ADRRESS, MQTT_PORT, network); // Create a handler for incoming messages mqtt.onMessage(messageHandler); Serial.print("ESP8266 - Connecting to MQTT broker"); while (!mqtt.connect(CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("."); delay(100); } Serial.println(); if (!mqtt.connected()) { Serial.println("ESP8266 - MQTT broker Timeout!"); return; } // Subscribe to a topic, the incoming messages are processed by messageHandler() function if (mqtt.subscribe(SUBSCRIBE_TOPIC)) Serial.print("ESP8266 - Subscribed to the topic: "); else Serial.print("ESP8266 - Failed to subscribe to the topic: "); Serial.println(SUBSCRIBE_TOPIC); Serial.println("ESP8266 - MQTT broker Connected!"); } void sendToMQTT() { StaticJsonDocument<200> message; message["timestamp"] = millis(); message["data"] = analogRead(0); // Or you can read data from other sensors char messageBuffer[512]; serializeJson(message, messageBuffer); mqtt.publish(PUBLISH_TOPIC, messageBuffer); Serial.println("ESP8266 - sent to MQTT:"); Serial.print("- topic: "); Serial.println(PUBLISH_TOPIC); Serial.print("- payload:"); Serial.println(messageBuffer); } void messageHandler(String &topic, String &payload) { Serial.println("ESP8266 - received from MQTT:"); Serial.println("- topic: " + topic); Serial.println("- payload:"); Serial.println(payload); // You can process the incoming data as json object, then control something /* StaticJsonDocument<200> doc; deserializeJson(doc, payload); const char* message = doc["message"]; */ }

Detailed Instructions

  • Copy the above code and open with Arduino IDE
  • Replace the WiFi information (SSID and password) in the code with your own.
  • Replace the MQTT broker address in the code (domain name or IP address).
  • Click Upload button on Arduino IDE to upload code to ESP8266

Send message from ESP8266 to PC via MQTT

ESP8266 codes publishes data to the MQTT topic esp8266-001/send, Subscriber Window on PC subscribe that topic to receive the data.

  • Open the Serial Monitor, you will see ESP8266 periodically publish a message to a topic.
COM6
Send
ESP8266 - Connecting to MQTT broker ESP8266 - Subscribed to the topic: esp8266-001/receive ESP8266 - MQTT broker Connected! ESP8266 - sent to MQTT: - topic: esp8266-001/send - payload:{"timestamp":10708,"data":311} ESP8266 - sent to MQTT: - topic: esp8266-001/send - payload:{"timestamp":15837,"data":298} ESP8266 - sent to MQTT: - topic: esp8266-001/send - payload:{"timestamp":20965,"data":291} ESP8266 - sent to MQTT: - topic: esp8266-001/send - payload:{"timestamp":26094,"data":286}
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Check the Subscriber Window, you will see that it receives the message published by ESP8266 as below:
Command Prompt
Microsoft Windows [Version 10.0.19045.3930] (c) Microsoft Corporation. All rights reserved. C:\WINDOWS\system32>cd /d D:\mqtt\mosquitto D:\mqtt\mosquitto>mosquitto_sub -h 192.168.0.26 -p 1883 -t esp8266-001/send Hello, MQTT! {"timestamp":10708,"data":311} {"timestamp":15837,"data":298} {"timestamp":20965,"data":291} {"timestamp":26094,"data":286}

Send message from PC to ESP8266 via MQTT

ESP8266 subscribes to the topic esp8266-001/receive, Publisher Window on PC publish a message to that topic to send it to the ESP8266.

  • Publish a message to the topic that ESP8266 subscribed by running the following command on Publisher Window:
mosquitto_pub -h 192.168.0.26 -p 1883 -t esp8266-001/receive -m "Hello, ESP8266!"
  • You will see this message is received by ESP8266 on Serial Monitor as below:
COM6
Send
ESP8266 - received from MQTT: - topic: esp8266-001/receive - payload: Hello, ESP8266!
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!