Login

Temperature and humidity monitoring using MQTT

Objectives

  • Interfacing the temperature and humidity sensor DHT11 with a NodeMCU
  • Communicate between our MQTT application and the NodeMCU.
  • Learn to publish and subscribe to different topics using Arduino IDE code.

Things

  1. NodeMCU board (quantity: 1 no.)
  2. Micro USB cable A to B (quantity: 1 no.)
  3. Breadboard (quantity: 1 no.)
  4. DHT11 temperature and humidity sensor (quantity: 1 no.)
  5. Jumper wire – male to male (quantity: 3 no.)
  6. WiFi router connected to the internet (quantity: 1 no.)
  7. MQTTBox software on your computer
  8. Arduino IDE on your computer

Let’s begin!

Message Queuing Telemetry Transport (MQTT)It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks. It is generally used for machine-to-machine communication.

To use MQTT on the NodeMCU, we will also need the PubSubClient library by Nick O’Leary. Install this on the Arduino IDE .

Sketch -> Include Library -> Manage Libraries… -> PubSubClient by Nick O’Leary.

We control the on-board LED of the NodeMCU (on pin 16) using MQTTBox.

  • Publishing a message as ‘0’ should switch on the LED
  • Publishing a message as ‘t’ will toggle the LED several times
  • Publishing any other message will switch off the LED.

We shall also publish the humidity and temperature readings from the DHT11 temperature and humidity sensor to an MQTT Client software every five seconds.

Installing MQTTBox

To use the MQTT protocol, we’ll require a helper program to develop and load test MQTT based clients, brokers, devices, cloud, and apps. We have used MQTTBox as our helper program.Let us now install and set up MQTTBox. Download the software from the official MQTTBox website: Download

Step 1: Download and Install MQTTBox from the link given. If warned about “File may be harmful” while downloading, click on “Keep file”. Run the installation.

Step 2: Once installed, it should open automatically. If not, open it from the Start menu. On first use, you should see a screen as shown below. Click on “Create MQTT Client”. Here we will setup the parameters of our MQTT client.

Step 3: Use any name you wish for the “MQTT Client Name”. We have used the name “Temp&Humid_Monitor” for our client.

Step 4: Set the “Protocol” to “mqtt/tcp”.

Step 5: Set the “Host” to “broker.mqtt-dashboard.com”. Click “Save”.

 

 

Interfacing DHT11 temperature and humidity sensor with NodeMCU

 

Interfacing DHT11 temperature and humidity sensor  with NodeMCU

 

The GND and Vin pin of the DHT11 sensor is connected to the GND and Vin pin of the NodeMCU respectively and the data pin of the DHT11 sensor is connected to the GPIO16/D0 pin of the NodeMCU.

Before uploading the code to the Arduino IDE, make sure that the DHT library is installed in your Arduino IDE.

Installing Arduino IDE and configuring for NodeMCU board functionality

To install the required files to program the NodeMCU using the Arduino IDE, follow the steps below.

Step 1: Download Arduino IDE from the official Arduino website: Download

Step 2: Install the software and connect the NodeMCU board to your computer using the micro USB cable.

Step 3: Start Arduino IDE and navigate to File -> Preferences.

Step 4: Copy the link below and paste it in the Additional Boards Manager URLs tab.

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

Click OK to close the preferences window.

Step 5: Navigate to Tools -> Board -> Boards Manager.

Step 6: In the Boards Manager window, type esp8266 by ESP8266 Community. Select it and install it onto the Arduino IDE

Step 7: Navigate back to Tools -> Board, find and select NodeMCU 1.0 (ESP-12E module) board.

Step 8: Go to Tools -> Port and choose the port that corresponds to your NodeMCU.

You can find this port number by opening the Device Manager from your computer’s Start Menu. From the list, look for the COM port number of USB-UART bridge or something similar.

In few computers, the UART port will not be present and hence cannot be detected, for that you have to download an USB to UART port converter from here.

 

Now that your installation process is completed, let us begin programming the NodeMCU using the Arduino IDE.

Coding on the Arduino IDE

In order to execute this project, we will use the following functions to code in the Arduino IDE.

In order to execute this project, we will use the following functions to code in the Arduino IDE.

void setup()

  • Any command you type in the void setup() function will only run once.
  • Syntax:

    void setup()
    {
      Type your command here;
    }

void loop()

  • Any command you type in the void loop() starts executing after void setup() is finished. The commands here will run infinite number of times unless you specify an exit condition to it.
  • Syntax:

    void loop()
    {
      Type your command here;
    }

int

  • Integers (int) are your primary data-type for pin numbers on Arduino. They can also be used for data storage.
  • Syntax: int var = val
  • ‘var’ indicates the int variable name.
  • ‘val’ indicates the value you assign to that variable (a pin number in most cases).

For this project: the following command is used to initialize all the pins and variables in the code.

int value = 0;

Note:

  • These variables are defined as int before void setup() in the Arduino IDE. Such variables which are defined outside void setup() and void loop() are called global variables.

pinMode()

  • A command pinMode() is used to set a specific pin to behave as either input or output.
  • Syntax: pinMode(pin,mode)
  • ‘pin’ indicates the specific pin number or a variable which denotes the pin number.
  • ‘mode’ can be either INPUT or OUTPUT.

For this project: the following commands set the pin as OUTPUT.

pinMode(16, OUTPUT);

digitalWrite()

  • A command digitalWrite() is an output command. It sets the output of a digital pin either HIGH or LOW.
  • Syntax: digitalWrite(pin,value)
  • ‘pin’ indicates the pin number or a variable which denotes a pin number.
  • ‘value’ of LOW or HIGH. If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

For this project: the following command writes value to a digital pin.

digitalWrite(16, HIGH);

delay()

  • A command delay()pauses the program for a definite period of time.
  • Syntax: delay(ms)
  • ‘ms’ is the number of milliseconds you want the delay for.

For this project: the following command pauses the code for 2 second.

delay(2000)

for()

  • A command for() is used to repeat a block of functions enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for() loop function is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
  • Syntax:

  for (initialization; condition; increment)
  {
  Type your commands here;
  }

  • The ‘initialization’ happens first and exactly once. Each time through the loop, the ‘condition’ is tested; if it is true, the statement block and the ‘increment’ is executed, then the ‘condition’ is tested again. When the ‘condition’ becomes false, the loop ends.

For this project: the following command repeats a block of statements enclosed in curly braces.

for(int tog = 0; tog < 20; tog++)

while()

  • A command while() will loop continuously, and infinitely, until the expression inside the parenthesis () becomes false.
  • Syntax: while(condition) 
  • ‘condition’ is a Boolean expression that evaluates to true or false.

For this project: the following command will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false.

while (!client.connected()) {

if()

  • The if() function checks for a condition and executes the proceeding statement or set of statements if the condition is ‘true’.
  • Syntax:

   if(condition) 
   {
   Type your command here;
   }

  • ‘condition’ is a boolean expression i.e., can be true or false.

For this project: the following command checks for a condition and executes the proceeding statement or set of statements if the condition is ‘true’.

if(client.connect("ESP8266Client")) {

else()

  • An else () clause (if at all exists) will be executed if the condition in the if statement results in false.
  • The else() can proceed another if() test, so that multiple, mutually exclusive tests can be run at the same time.
  • Syntax: else()

For this project: the following command the clause will be executed if the condition in the if statement results in false.

else {
client.publish("MESSAGE_OUT", detail); 
Serial.println(detail);
}

Serial.begin()

  • A command Serial.begin() sets the data rate in bits per second (baud) for serial data transmission.
  • Syntax: Serial.begin(speed)
  • ‘speed’ indicates the speed in bits per second (baud) – long.

For this project: the following command set the baud rate to 115200.

Serial.begin(115200);

Serial.print()

  • A command Serial.print() prints data to the serial port as human-readable ASCII text.
  • Syntax: Serial.print(val)
  • ‘val’ indicates the value to print – any data type.

For this project: the following command prints the ldr value to the serial port.

Serial.print("Connecting to ");

Serial.println()

  • A command Serial.println() prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or ‘\r’) and a newline character (ASCII 10, or ‘\n’).
  • Syntax: Serial.println(val) 
  • ‘val’ indicates the value to print – any data type.

For this project: the following command prints the map_ldr value to the serial port.

Serial.println("Successfully Connected"); 

float

  • A command float is a datatype for floating-point numbers, a number that has a decimal point.
  • Syntax: float var=val;
  • ‘var’ indicates your float variable name.
  • ‘val’ indicates the value you assign to the variable.

For this project: the following command is a datatype for floating-point numbers, a number that has a decimal point.

float humidity, temp_c;

 

For this project: we will now summarize the above mentioned functions.

  • Using digitalWrite(), delay(), while(), Serial.begin(), Serial.print() and Serial.println(), the void setup() will look like this. 
void setup() {
pinMode(16, OUTPUT);              
digitalWrite(16, HIGH);              
Serial.begin(115200);                   
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}                
Serial.println("WiFi connected");       
client.setServer(mqtt_server, 1883);   
client.setCallback(callback);      
dht.begin();
}
  • Using  if(), the void loop() will look like this.
void loop() {
if(!client.connected()) {
reconnect();
}
client.loop();
long now = millis();                           
if(now - lastMsg > 5000)  {                   
lastMsg = now;
++value;
gettemperature();
}
}

Final code

Our final code will look like this.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Uploading the code

Step 1: Enter the final code in the Arduino IDE window.

  • When you click on New to open a new blank code in the Arduino IDE, you will get a new  window with two functions: void setup() and void loop()
  • You can either type commands as shown in the final code under void setup() and void loop() functions or 
  • Delete the contents of this window. Then copy and paste the final code in the Arduino IDE window.

Step 2: Compile/ verify the code by clicking on the verify button.

  • Make sure the Arduino Uno is connected to your computer
  • Check if the correct board and port is selected.

Step 3: Upload the code by clicking on the upload button, which is right next to the verify button.

  • The Arduino IDE provides a progress bar when it’s uploading.
  • After it is done, you will see “Done uploading” on the bottom left of your IDE.
  • If you encounter any errors, you need to go back to the code and fix the errors.

There you go!

After uploading the code to your NodeMCU device, setting up your MQTT Client and inputting the correct publish/subscribe topics in the relevant forms, your MQTTBox client screen will be as below.

On the left side (publish), we have the following parameters:

  • Topic to publish: Name of your topic
  • Quality of Service (QoS): 2 is the safest but slowest, 0 is the fastest but most unreliable
  • Payload type: The type of values you’ll be transmitting via MQTT
  • Payload: The data being published to the NodeMCU

On the right side (subscribe), we have just one parameter to input:

  • Topic to subscribe to: This is declared in our code as ‘MESSAGE_OUT’
  • According to the delay we’ve set in the code, the temperature and humidity readings will be published to this topic every 5 seconds along with the reading number as ‘TESTING #’ followed by the reading number. This number will reset when the NodeMCU is restarted.
  • If there is an error in the reading (such as if the DHT11 is not connected or the reading is out of bound), then an error message, “Failed to read from DHT sensor!” (as shown in the screenshot above) will appear.

The MQTTBox is subscribed to “MESSAGE_OUT”. The DHT values are regularly published on this topic by the NodeMCU. The values can be seen by subscribing to this topic. The NodeMCU is subscribed to “BUILTIN_LED”. The on-board LED can be controlled by publishing to this topic.

While connected, publishing any string beginning with:

  • ‘0’ will switch ON the on-board Blue LED

 

On-board Blue LED ‘ON’

 

  • ‘t’ will toggle the LED several times and end with the LED OFF

 

On-board Blue LED ‘toggle’

 

  • any character excluding ‘0’ and ‘t’ will switch OFF the LED

 

On-board Blue LED ‘OFF’

 

Tinker with the code, connect input devices such as other LEDs or motors and control them remotely. Explore the possibilities!

 

Takeaway

 

Loader Loading...
EAD Logo Taking too long?
Reload Reload document
| Open Open in new tab

Enrich

Installing Arduino IDE

Explore

What is MQTT ?

Client Functions

We would love to see what you build out of these learnings!

Click here to submit your projects, share it with the world and stand a chance to be rewarded.

top

Knowledge and Content by Li2 Technologies | © 2021 NASSCOM Foundation | All rights reserved

X