Build your own cloud-connected temperature and humidity monitor in 30 minutes for less than $20!
GARRETT SCHMIDT
Automating the Power Grid of the Future | Wireless & 4G/5G | Industrial Protocols | Master Tinkerer | Ghostbuster
This tutorial assumes you have no experience using Arduino and is a great way to try out what you’ve learned about MQTT.
In this exercise, you’ll assemble some basic hardware, configure it using some sample code, and then publish data to a simple dashboard in the cloud.
Required Hardware
The ESP8266 based NodeMCU module has built-in Wifi connectivity and can be programmed using the Arduino IDE. These can be purchased for a few dollars on Amazon, buy 1 or buy a 3 pack if you want to build a few:
https://www.amazon.com/gp/product/B010O1G1ES/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&th=1
You’ll also need a temperature and humidity sensor, you can grab a 5-pack for a few dollars. The DHT11 sensor is very easy to work with, and these include jumper wires you can use to connect it to the NodeMCU module.
https://www.amazon.com/gp/product/B07V5MTQJG/ref=ppx_yo_dt_b_asin_title_o06_s00?ie=UTF8&psc=1
Optionally, you can pick up a breadboard and jumper wire kit. This makes the assembly a bit nicer and more “professional” but it’s not absolutely necessary.
The last piece of hardware you’ll need is a micro USB cable, which you probably have in a drawer somewhere. If you don’t, pick one up on Amazon while you’re there.
Install the Software
While you’re waiting for your package to arrive, you can set up the software. Download the Arduino IDE and install it. Be sure to get the right version for your computer’s operating system.
https://www.arduino.cc/en/main/software
After installation is complete, open the Arduino IDE, we need to install some libraries that the project requires.
Open the Sketch menu, then Include Library, then click Manage Libraries.
This will open the Library Manager. In the search box, type “ArduinoMQTTClient.” The search results should show a library called ArduinoMQTTClient by Arduino. Click the button to install it.
Next, search for “Adafruit Unified Sensor” and install that library. You may need to scroll through the search results to find it.
Lastly, search for “DHT” and install the library called “DHT sensor library by Adafruit.”
Close the Library Manager. Go to File and click “Preferences.” In the “Additional Boards Manager URLs” text box, enter the following URL:
https://arduino.esp8266.com/stable/package_esp8266com_index.json
Click “OK” and close the Arduino IDE.
Assemble the Hardware
By now, your hardware should have arrived from Amazon. You’ll need to do a little wiring to connect the DHT sensor to the NodeMCU.
If you opted to buy the breadboard, you’ll notice each row is numbered, and the columns have letters. The columns and rows are grouped. Columns A through E are electrically connected in a given row, while columns F through I are connected. This allows you to make multiple common electrical connections in each row. Plug the NodeMCU into the breadboard. Then plug the DHT sensor into the board so that the three pins are each in their own numbered row. Make sure that the DHT sensor and NodeMCU are not sharing any common rows at this point. Use the jumper wires to connect the “+” pin on the sensor to the ”3V” pin on the NodeMCU. Connect the “Out” pin to “D2”, and the “-“ pin to “GND.”
If you didn’t buy the breadboard, use the jumper wires included with the DHT sensor to make the connections directly between the sensor and the NodeMCU.
Connect the NodeMCU to your computer using the USB cable. The USB driver should be automatically installed. If there is a problem, you can manually download and install the driver from:
https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
Once the driver is installed, open your device manager to see what COM Port number was assigned to it. On Windows 10, you can click the Windows start button and start typing “Device Manager.”
Under “Ports,” you should see “Silicon Labs CP210x USB to UART Bridge (COMxx)” where indicates the COM Port number that was assigned to the device.
Download the code
You’ll need the code (referred to as a sketch) to make your NodeMCU do the magical things it does. You can download my sample program from Github. Make sure you correctly save it as a .ino file.
https://github.com/grschmid/MQTT-tutorial
Start the Arduino IDE. Go to File, Open, and select the simple_MQTT_test.ino file. You will be prompted to create a folder for your project. Select “OK” to continue.
Open the “Tools” menu, “Port” and select the COM Port number of the NodeMCU device.
Open the “Tools” menu, “Boards” and select “NodeMCU 1.0 (ESP-12E Module).”
Now we’re going to compile the code to make sure everything is configured correctly. Click the checkmark button in the upper left, and wait while the code compiles. With a little luck, it will compile correctly. If errors are generated, review the previous steps to be sure you didn’t forget to install a library.
Additionally, you can check the code itself for clues. The lines of code are numbered. Lines 16, 17, and 18 contain references to the libraries we installed earlier. The “*.h” file references should have orange text (see below). If any of these are not orange, it could indicate the library was not installed, or you have not selected the correct NodeMCU board.
If the code compiles without errors, congratulations, you are now ready to start programming!
Configure the Sketch
A few lines of code need to be modified for your use.
Line 21 is where you should enter the SSID of your Wifi network. Be sure to keep the quotes “ “ around the SSID and any other variables that currently have them. The quotes tell the code that these are strings of text.
Enter your Wifi password on line 22.
Lines 23-29 are for the configuration of the MQTT communication. We’re going to start by communicating with an MQTT broker called Hive and viewing the data in your web browser using MQTT over web sockets.
Open your web browser and go to https://www.hivemq.com/demos/websocket-client/
You’ll see a simple screen with a number of text boxes for configuration. Copy the host field (broker.mqttdashboard.com) and paste it into your code as the broker on line 23.
On line 24, enter 1883 as the port.
Since the Hive broker doesn’t require any user credentials, the MQTT user name and password on lines 25 and 26 should be empty, so just leave the quotes. You can enter any value for the client ID, which acts as a unique identifier to the MQTT broker.
Now you can configure the MQTT topic names in lines 28-30 for the 3 variables we are interested in. Topic 1 contains the temperature measurement from the DHT sensor. Topic 2 contains the humidity measurement, and Topic 3 allows us to control the blue LED on the NodeMCU. You can leave them as they are or customize them to your liking. The topic naming convention is similar to the file directory structure of Windows, using the “/” to create a “sub-topic” structure of sorts. To explore the capabilities of MQTT, try entering your name before the “/” to create a unique topic name, e.g. “grschmid/temp”.
Lastly, we set the rates at which we send and read data. Samplerate1 on line 31 sets the publish rate for the temperature and humidity data. Samplerate2 on line 32 sets the rate at which we check the broker for updates to the blue LED state. Use some common sense when setting these values as some brokers have limitations about the update rates. Both samplerate1 and samplerate2 are entered in milliseconds, where 5000 equals 5 seconds.
The code is now configured, and you’re ready to load it to your device. First, go to the Tools menu and click on Serial Monitor. This will open a dialog box so we can locally monitor what the device is doing after the code is loaded. In the lower right-hand corner, make sure the baud rate is set to 115200 baud.
Now go back to the code editor window and click the arrow pointing to the right in the upper left-hand corner to load the code onto the device. It will take a few seconds to compile and load. You can watch the status in the dialog box along the bottom of the screen.
When it’s done loading, you’ll see a message like this:
Switch back to the serial monitor and watch the status. You’ll see it go through steps to connect to the Wifi network and then the MQTT broker. Assuming everything is successful, you’ll then see temperature and humidity measurements start to appear.
If the Wifi or MQTT broker connections fail, errors will be reported. Go back to the code editor and check for typos. Correct any mistakes and reload the code.
Once everything’s appearing correctly, let’s go back to our web socket client.
Click Connect to connect to the broker.
Click Add New Topic Description, and enter the topic names from your code. If you used your name as the topics settings, just enter your_name/#, and set the QoS value to 0. Click Subscribe.
You should immediately see data start to appear in the Messages box. Congratulations, you’re publishing data to the cloud!
Now you can control the LED. In the Publish field, enter the LED topic name, enter a “1” without quotes in the Message field, and click Publish. You should see the blue LED on your nodeMCU device light up. Enter a “0” to turn the LED off. Congratulations, you’ve subscribed to data from the cloud!
Building a Dashboard
Moving data back and forth to the cloud is fun, but a beautiful dashboard is much more exciting to look at than a bunch of text boxes. So let’s build one using the Adafruit IO cloud. It’s easy and free, perfect for this learning experience. Launch your web browser and go to adafruit.io, where you’ll need to create an account.
Now you’ll need to make some changes to your NodeMCU program in order to connect to the Adafruit MQTT broker. In the Arduino IDE, change the broker name on line 23 to “io.adafruit.com”. The MQTT user name on line 23 is your Adafruit IO user name, and the MQTT password (line 26) is your Adafruit IO key, which you can get by clicking on “Adafruit IO Key” in the upper right-hand corner of the Adafruit IO page. It’s a long, alphanumeric string, so use copy and paste to avoid errors.
Lastly, the MQTT topics need to be in a specific format on lines 28-30. They must be entered as “username/feeds/topic” where the username is your Adafruit IO user name, and the word topic can be customized as you see fit. After the changes are made, upload your sketch to the NodeMCU and use the serial monitor to confirm your connection.
Now, head back to Adafruit IO, where we’ll set up our dashboard. Click “Dashboards” and choose "Create a New Dashboard" from the Actions dropdown box. Give it a clever name and description, then click Create.
Click on the dashboard name to open it, and you’ll be presented with a mostly blank canvas upon which to build.
Now we’ll add some widgets. Click the “+” button in the upper right and select a widget for your temperature measurement. The line chart or gauge is a good choice. Next, you’ll be prompted to choose a feed for this widget. Enter the last part of the MQTT topic name you programmed into the NodeMCU for the temperature topic (the part after “/feeds/” e.g. temp) and click create. That will appear in the table at the bottom of the screen. Make sure it’s checked and click "Next step" to do the final configuration of the widget.
When you’re done, click Create Block to finalize your widget. Data should begin to populate your widget immediately. Repeat this process to create a widget for the humidity.
Use a “Toggle” widget for controlling the blue LED on your NodeMCU. Create the feed, and on the “Block Settings” screen, enter a “1” for Button On Text, and “0” for Button Off Text. This will send a 1 to turn on the LED and a 0 to turn it off.
Enjoy your new IOT dashboard.
You can adjust the privacy settings of the dashboard and feeds to make the dashboard accessible from anywhere without logging into your account.
Note: The free tier of Adafruit IO has a strict limit on the rate at which messages may be published, so use caution when setting the sample rates in the Arduino sketch, or risk the MQTT broker temporarily banning you!
B2B Demand Generator | GTM Master | Director of Product Marketing | Life-long Student of Life
3 年Impressive! Very well done, Garrett.?
"International Man of Mr.IIoT"
3 年Wow - Great, in depth how-to guide Garrett! Well done, and THANK YOU!