Getting Started with MQTT on Arduino Using NodeMCU ESP8266
In this tutorial, I will show you how to use the Arduino IDE to program an ESP8266 microcontroller to read sensor data and publish it using MQTT to a HiveMQ Cloud MQTT broker.
Further, I’ll show you how to receive MQTT messages as commands from the cloud and activate the microcontroller output to switch ON and OFF a Light Emitting Diode (LED).
What are ESP8266 NodeMCU Unit and DHT11 Sensor?
Let us look briefly at the hardware components we will use for this demo, the NodeMCU Micontroller Unit, and the DHT11 Temperature and Humidity Sensor.
Based on the ESP8266 WLAN chip, the NodeMCU is a small, fast, and 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 various serial interfaces such as SPI, I2C, or RS232.
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 for transmitting the sensor data to the NodeMCU microcontroller.
Hardware Wiring and Circuit Diagram
Next, let’s look at how to wire the hardware components for this demonstration.
The image above shows the setup for this demonstration, and the one below shows the visualization of the specific connection using a circuit diagram.
As shown, the connections are as follows:
Vcc of the DHT11 goes to +3v of the NodeMCU,
Signal pin of the DHT11 goes into the Digital Pin GPIO2 of the NodeMCC, and the
Ground pin of the DHT11 goes into the Ground Pin of the NodeMCU.
A resistor connects the LED to the NodeMCU digital pin, GPIO5.
Setting Up a HiveMQ Cloud MQTT Broker
Since I’ll be publishing MQTT messages from the NodeMCU board to an MQTT Broker, I must create the MQTT Broker on HiveMQ Cloud and retrieve the broker details to use in the Arduino code.
I’ll go to the HiveMQ website's mega menu and click on ‘Login.’
We are taken to a sign-up page and prompted 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’ll need to provide an email address and password and follow the simple steps to confirm your email and create your account.
An MQTT broker cluster will automatically be created when you’ve successfully created your account. Start by setting up credentials to allow devices to connect to your MQTT broker.
So, I’ll define the username and password and click on ADD.
Clicking on ‘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 for use in my Arduino code.
If I wish to update my connection credentials, I can always log in to my portal, click on ‘MANAGE CLUSTER,’ and select ‘ACCESS MANAGEMENT.’
Installing and Configuring Arduino IDE
Downloading and Installing
Next, we program the ESP8266 NodeMCU board using Arduino IDE. You can download Arduino IDE by going to the Software downloads page of their website.
For this demonstration, I’ll download Arduino for Windows and install it.
Enabling Support for the ESP8266 chip
After installing the Arduino IDE, you can program various 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 Boards Manager’ field, I’ll enter this URL:
https://arduino.esp8266.com/stable/package_esp8266com_index.json.
Then click OK.
Next, go to the ‘Tools’ menu, and select ‘Board’, followed by ‘Boards Manager’.
Look for ESP8266, select it, and click on the Install button.
Connecting the NodeMCU Board to the Arduino IDE Via USB
Next, I need to specify the ESP8266 board I want to program in the Arduino IDE. So, I’ll connect my NodeMCU board to my PC using a micro USB cable with my Windows Device Manager open.
As soon as I plug in my board, a new COM port appears on the Device Manager.
If you experience problems with your USB drivers, Windows Device Manager can help you troubleshoot. However, generally, it doesn’t need to be open. You can usually access the COM port by going to the Port menu item under tools in the Arduino IDE.
To select the board for programming, go to the ‘Tools’ menu item, followed by ‘Board,’’ and then NodeMCU 12 module.
Now we are ready to start programming my NodeMCU using the Arduino IDE.
Installing Required Software Libraries
Before moving directly to coding, let’s install the required libraries.
Installing DHT Sensor Library
You must install the DHT sensor library available from the Arduino library manager to read sensor data.
So navigate to Sketch > Include Library > Manage Libraries.
Search for DHT and choose one from a number of DHT libraries.
Installing MQTT Client Library
We need an MQTT Client library to publish MQTT messages to my HiveMQ Cloud MQTT Broker. For this demonstration, we will use a library called PubSubClient. To add it, I’ll go to Sketch > Include Library > Manage Libraries and search for PubSubClient.
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 required libraries, let’s go through the code for sending and receiving MQTT messages using NodeMCU on the Arduino platform.
First, I import the required libraries into my Arduino code.
Next, declare GPIO2 as the pin to which my DHT sensor is connected. Also, declare GPIO5 as the pin to which the LED is connected.
After that, we declare variables for holding the Wi-Fi connection and HiveMQ Cloud MQTT Broker details
Then I make sure to initialize a secure Wi-Fi client connection, create an MQTT client using PubSubClient library and attach it to the secure Wi-Fi connectivity. Also, here I declare MQTT message buffer variables.
Now that we’ve set our connectivity, we can declare a variable for holding a root certificate that allows the client to connect securely to the HiveMQ Cloud MQTT broker.
Then, we will declare the function that we will use to connect to the WiFi network.
Next, we set a function for esp8266 connecting to the HiveMQ Cloud MQTT broker.
Then let’s add a callback method for receiving MQTT messages and switching the LED ON and OFF.
After that, I implement a method for publishing MQTT messages to my HiveMQ Cloud MQTT broker.
We move to the default Arduino setup method, where we set up the DHT 11 sensor and LED, enable the certificate for a secure connection, setup up Wi-Fi, and create instances of the MQTT server and callback methods.
Finally, we are ready to add the main function for executing the application 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, including deviceId and siteId properties, into a JSON object.
After serialization, I publish the JSON string to my HiveMQ Cloud MQTT Broker under the topic “esp8266_data”, and repeat the process every 5 seconds.
Next, deploy this code onto 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.
I will use MQTT.fx for testing my MQTT connection. 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.
Seeing data flowing means you are successfully publishing data from the NodeMCU using MQTT.
Now, I will publish an MQTT command to switch on the LED light from MQTT.fx by publishing the value of “1” under the topic “led_state”. When I do that, you can see the LED light switch ON.
To switch the light off, publish a value of “0”.
Conclusion
Together, we have experienced 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 out the above demonstration and get started with building MQTT applications by signing up for a free HiveMQ Cloud account.
Take your MQTT projects to the next level with HiveMQ Cloud Starter. Experience unmatched performance and reliability with our 15-day free trial, no credit card required. Watch our webinar, Accelerating Your IoT Project in the Cloud From Idea to Production in Under 5 Minutes, to learn how to make MQTT work for you, from proof-of-concept to early production, using HiveMQ Cloud.
Check out the video below that provides the summary of this blog
Chapters
- 00:40 - Introduction to ESP8266 NodeMCU Unit and DHT11 Sensor
- 01:33 - Hardware Wiring and Circuit Diagram
- 02:10 - Setting up a HiveMQ Cloud MQTT Broker
- 04:10 - Installing and Configuring Arduino IDE
- 07:15 - Installing Required Software Libraries
- 08:08 - Programming NodeMCU to Send and Receive MQTT Messages
Kudzai Manditereza
Kudzai is a tech influencer and electronic engineer based in Germany. As a Sr. Industry Solutions Advocate at HiveMQ, he helps developers and architects adopt MQTT and HiveMQ for their IIoT projects. Kudzai runs a popular YouTube channel focused on IIoT and Smart Manufacturing technologies and he has been recognized as one of the Top 100 global influencers talking about Industry 4.0 online.