Introduction to MQTT on Arduino using NodeMCU ESP8266 (2023)

Introduction to MQTT on Arduino using NodeMCU ESP8266 (1) Introduction to MQTT on Arduino using NodeMCU ESP8266 (2) Introduction to MQTT on Arduino using NodeMCU ESP8266 (3)

In this tutorial, I will show you how to use Arduino IDE to program an ESP8266 microcontroller to read sensor data and publish it using MQTT to a HiveMQ Cloud MQTT broker.

In addition, I'll show you how to receive MQTT messages as commands from the cloud and activate the microcontroller's output to turn a light-emitting diode (LED) on and off.

What is NodeMCU ESP8266 unit and DHT11 sensor?

Let's briefly look at the hardware components we'll be using for this demo, the NodeMCU Micontroller unit and the DHT11 temperature and humidity sensor.

Based on the ESP8266 WLAN chip, NodeMCU is a small, fast, Wi-Fi capable microcontroller board. You can easily program it in the popular Arduino Integrated Development Environment (IDE). It has many input/output ports and several serial interfaces such as SPI, I2C or RS232.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (5)NodeMCU microcontroller board and DHT11 sensor

The DHT11 is a sensor capable of measuring the relative humidity and temperature of the surrounding environment. It consists of three pins, two for power and one is a signal line to transmit the sensor data to the NodeMCU microcontroller.

Hardware Wiring and Circuit Diagram

Next, we'll see how to connect the hardware components for this demo.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (6)

The image above shows the setup for this demo, and the image below shows the visualization of the specific connection using a circuit diagram.

As shown, the connections are as follows:

  • Vcc from DHT11 goes to +3v from NodeMCU,
  • The DHT11 signal pin goes to the GPIO2 digital pin of the NodeMCC and the
  • The DHT11 ground pin goes to the NodeMCU ground pin.
  • A resistor connects the LED to the NodeMCU digital pin, GPIO5.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (7)

Configuring a HiveMQ Cloud MQTT Broker

Since I will be publishing MQTT messages from the NodeMCU board to an MQTT Broker, I must create the MQTT Broker in HiveMQ Cloud and retrieve the broker details to use in the Arduino code.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (8)

I'm going toSite do HiveMQand select 'Cloud'on the menu. I'll get theHiveMQ Cloudpage and then click the 'Try it for free'button. If you want, you cansign up for HiveMQ Cloud directly here.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (9)

We're taken to a sign-up page and asked to create a free account that allows us to connect up to 100 devices.

If you are accessing the HiveMQ Cloud portal for the first time, you will need to provide an email address and password and follow the simple steps to confirm your email and create your account.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (10)

An MQTT broker cluster will be created automatically when you successfully create your account. Start by configuring credentials to allow devices to connect to your MQTT agent.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (11)

So I'm going to set the username and password and click onTO ADD.

Clicking 'Clusters'will provide the list of my MQTT broker clusters. Since I just created this account, I only have one. So my MQTT broker setup is ready. Now I need to get the cluster URL, port number and access credentials to use in my Arduino code.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (12)

If I want to update my connection credentials, I can always login to my portal, click on 'MANAGE CLUSTER' and select 'ACCESS MANAGEMENT'.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (13)

Installing and Configuring the Arduino IDE

Downloading and Installing

Next, we program the ESP8266 NodeMCU board using the Arduino IDE. You can download the Arduino IDE by accessing the SoftwareTransferspage of their website.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (14)

For this demo, I'm going to download Arduino for Windows and install it.

Enabling support for the ESP8266 chip

After installing the Arduino IDE, you can program multiple Arduino boards. However, to program a NodeMCU board instead of an Arduino board, you will need to add a package to the IDE's board management system.

To do this, go to the 'File'menu and select 'Preferences.'

Then under the 'Additional Board Manager'field, I would enter this URL:

https://arduino.esp8266.com/stable/package_esp8266com_index.json.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (15)

Then click OK.

Then go to the 'Tools'menu and select 'Quadro', followed by 'Council Manager'.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (16)

Search for ESP8266, select it and click the Install button.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (17)

Connecting the NodeMCU Board to the Arduino IDE via USB

Next, I need to specify the ESP8266 board that I want to program in the Arduino IDE. So I'm going to connect my NodeMCU board to my PC using a micro USB cable with Windows Device Manager open.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (18)

As soon as I plug in my card, a new COM port appears in Device Manager.

If you have problems with your USB drivers, Windows Device Manager can help you troubleshoot the problem. However, it usually does not need to be opened. Normally, you can access the COM port by going toPortamenu item under Tools in the Arduino IDE.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (19)

To select the board for programming, access the menu ‘Tools'menu item, followed by 'Quadro,''and then the NodeMCU module 12.

We are now ready to start programming my NodeMCU using the Arduino IDE.

Installing the necessary software libraries

Before moving directly to coding, let's install the necessary libraries.

Installing the DHT sensor library

You must install DHT sensor library available in Arduino library manager to read sensor data.

Then navigate to Sketch > Include Library > Manage Libraries.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (20)

Search for DHT and choose one of several DHT libraries.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (21)

Installing the MQTT Client Library

We need an MQTT Client library to publish MQTT messages to my HiveMQ Cloud MQTT Broker. For this demo, we'll use a library called PubSubClient. To add it, I'll go to Sketch > Include Library > Manage Libraries and look for PubSubClient.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (22)

There are many to choose from. I'll add this one from Nick O'Leary.

Programming NodeMCU to send and receive MQTT messages

Now that we've installed the necessary libraries, let's move on to the code for sending and receiving MQTT messages using NodeMCU on the Arduino platform.

First, I import the necessary libraries for my Arduino code.

#ifdef ESP8266 #include  #other #include #end if#include "DHTesp.h"#include #include #include 

Then declare GPIO2 as the pin my DHT sensor is connected to. Also declare GPIO5 as the pin the LED is connected to.

/**** DHT11 sensor settings *******/#define DHTpin 2//Configure the DHT pin as GPIO2DHTesp dht;/**** LED Settings *******/const int led = 5; //Define the LED pin as GPIO5

After that we declare variables to hold Wi-Fi connection and HiveMQ Cloud MQTT Broker details

/****** Wi-Fi connection details ********/const Characters* ssid = "your_wifi_ssid";const Characters* password = "your_wifi_password";/*********** MQTT agent connection details *******/const Characters* mqtt_server = "34bab4bb63014dce9e71f4ad8fb6ffc2.s2.eu.hivemq.cloud";const Characters* mqtt_username = "your_mqtt_client_username";const Characters* mqtt_password = "your_mqtt_client_password";const int mqtt_port =8883;

Next, I make sure to initialize a secure Wi-Fi client connection, create an MQTT client using the PubSubClient library, and attach it to secure Wi-Fi connectivity. Also, here I declare MQTT message buffer variables.

/**** Secure Wi-Fi Connectivity Initialization *****/WiFiClientSecure espClient;/**** MQTT client startup using WiFi connection *****/PubSubClient client(espClient);not signed longo last message = 0;#define MSG_BUFFER_SIZE (50)Characters msg[MSG_BUFFER_SIZE];

Now that we've defined our connectivity, we can declare a variable to hold a root certificate that allows the client to securely connect to the HiveMQ Cloud MQTT broker.

/****** root certificate *********/static const Characters *root_ca PROG = R"EOF(-----TO START CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55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vgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/and R44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----FIM CERTIFICATE-----)EOF";

Then declare the function we will use to connect to the WiFi network.

/*************** Connect to Wi-Fi ***********/empty setup_wifi() { delay(10); Serial.print("\nConnecting to "); Serial.println(ssid); Wi-fi.way(WIFI_STA); Wi-fi.to start(ssid, password); while (Wi-fi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } randomSeed(micros()); Serial.println("\nwifi connected\nIP address: "); Serial.println(Wi-fi.localIP());}

We then define a function for esp8266 connecting to the HiveMQ Cloud MQTT broker.

/*************** Connect to MQTT Broker ***********/empty reconnect() { // Loop I reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); Corda Customer ID = "ESP8266Client-"; // Create a random customer ID Customer ID += Corda(random(0xffff), HEX); // Try to connect with (client.to connect(Customer ID.c_str(), mqtt_username, mqtt_password)) { Serial.println("connected"); client.subscribe("led_state"); // subscribe to topics here } other { Serial.print("failure, rc="); Serial.print(client.state()); Serial.println("try again in 5 seconds"); // Wait 5 seconds before trying again delay(5000); } }}

Next, let's add a callback method to receive MQTT messages and turn the LED on and off.

/***** Callback method for receiving MQTT messages and toggling the LED ****/empty call back(Characters* him, byte* useful load, not signed int length) { Corda message received = ""; for (int eu = 0; eu < length; eu++) message received+=(Characters)useful load[eu]; Serial.println("Message arrived ["+Corda(him)+"]"+message received); //--- check the received message with( strcmp(him,"led_state") == 0){ with (message received.it's the same as("1")) digitalWrite(led, ALTO); // Liga o joint other digitalWrite(led, LOW); // turn off the LED }}

After that I implemented a method to publish MQTT messages to my HiveMQ Cloud MQTT broker.

/**** Method for publishing MQTT messages **********/empty post message(const Characters* him, Corda useful load , boleano retained){ with (client.post(him, useful load.c_str(), TRUE)) Serial.println("Posted message ["+Corda(him)+"]: "+useful load);}

We move on to the standard Arduino configuration method, where we configure the DHT 11 sensor and LED, enable the certificate for a secure connection, configure Wi-Fi, and create instances of the MQTT server and callback methods.

/**** Application startup function******/empty to set up() { dht.to set up(DHTpin, DHTesp::DHT11); //Configure the DHT11 sensor pinMode(led, EXIT); // configure the LED Serial.to start(9600); while (!Serial) delay(1); setup_wifi(); #ifdef ESP8266 espClient.definirInseguro(); #other espClient.definirCACert(root_ca); // enable this line and "certificate" code for secure connection #end if client.setServer(mqtt_server, mqtt_port); client.setCallback(call back);}

Finally, we're ready to add the main function to execute the application's logic. If you are not connected, connect the MQTT client to the HiveMQ Cloud MQTT broker. Then read the temperature and humidity values ​​from the DHT11 sensor and serialize them includingdevice IDeID do siteproperties, into a JSON object.

After serialization, I publish the JSON string to my HiveMQ Cloud MQTT Broker in topic “esp8266_data” and repeat the process every 5 seconds.

/********** Main function *************/empty link() { with (!client.connected()) reconnect(); // check if the client is connected client.link();//read the DHT11 temperature and humidity reading delay(dht.getMinimumSamplingPeriod()); float moisture = dht.getHumidity(); float temperature = dht.getTemperature(); DynamicJsonDocument document(1024); document["device ID"] = "NodeMCU"; document["ID do site"] = "My Demo Lab"; document["moisture"] = moisture; document["temperature"] = temperature; Characters mqtt_message[128]; serializeJson(document, mqtt_message); post message("esp8266_data", mqtt_message, TRUE); delay(5000);}

Then implant this code into the microcontroller board.

Now that my code is running and I'm publishing data to the HiveMQ Cloud MQTT Broker, I can use an MQTT Client application such as MQTTfx to subscribe to the broker and view the data.

When I open my MQTT.fx application, which is already connected to the HiveMQ Cloud MQTT broker and subscribed to the same topic, I can see the data coming in.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (23)

Seeing the data flowing means you are successfully publishing data from NodeMCU using MQTT.

Now, I will publish an MQTT command to turn on the MQTT.fx LED light by publishing the value of “1” in the “led_state” topic. When I do that, you can see the LED light on.

Introduction to MQTT on Arduino using NodeMCU ESP8266 (24)

To turn off the light, post a value of “0”.

Conclusion

Together, we experimented with using the Arduino IDE to program an ESP8266 microcontroller to send and receive MQTT messages from a HiveMQ Cloud MQTT broker. How was the process for you? Can you see other use cases?

Try the demo above and start creating MQTT applications by signing up for a free HiveMQ Cloud account.

Check out the video below which provides the summary of this blog

Introduction to MQTT on Arduino using NodeMCU ESP8266 (25)

Sobre Kudzai Mantereza

Kudzai is a Developer Advocate at HiveMQ and the founder ofIndustry40.tv. He hosts an IIoT Podcast and is involved in Industry4.0 research and education efforts.

Top Articles
Latest Posts
Article information

Author: Golda Nolan II

Last Updated: 06/24/2023

Views: 6174

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.