ESP32-DHT11 temperature and humidity data upload to MQTT server

ESP32-DHT11 temperature and humidity data uploaded to MQTT server

  • Introduction
    • ESP32
    • DHT11
  • experiment
    • Experiment instructions
    • wiring
    • MQTT server
      • establish connection
      • Add subscription
    • ESP32 drives DHT11
    • ESP32 sends data to MQTT server
    • Upload temperature and humidity data
    • Experimental results

Introduction

ESP32


Click on the image to purchase

The ESP32 series modules integrate Wi-Fi, traditional Bluetooth and low-power Bluetooth functions and have a wide range of uses: Wi-Fi supports a wide range of communication connections and also supports direct connection to the Internet through routers, while Bluetooth allows users to connect to mobile phones or broadcasts Bluetooth LE Beacon facilitates signal detection and can quickly build IoT projects.
This experiment used the ESP32-WROOM-32 development board, which uploaded sensor data to the MQTT server through wifi networking.

DHT11


Click on the image to purchase

DHT11 digital temperature and humidity sensor is a temperature and humidity composite sensor with calibrated digital signal output. The sensor uses a resistive humidity sensing element and an NTC temperature measuring element, and is connected to the microcontroller through a single-wire serial interface and developed to achieve stability. Reliable temperature and humidity measurement.

Experiment

MQTT is a lightweight and flexible message exchange and data transfer protocol for the Internet of Things. The purpose of this experiment is to drive DHT11 through ESP32 and upload the temperature and humidity data of DHT11 to the MQTT server to achieve remote monitoring.

Experimental instructions

The experiment requires the use of an MQTT server. It would be a waste to build it yourself or buy it just for experiments. You can find free and open MQTT servers online, which are completely sufficient for experiments. This experiment will use the free MQTT server on EMQ X Cloud. Therefore, you need to install the MQTT X software on your computer and prepare the DHT11 and ESP32 development boards.

Wiring

ESP32 DHT11
5V V
GND G
GPIO5 D

MQTT server

Establish connection

First, connect the MQTT server on the computer. First, download and install the MQTT X portal. After installation, open it and click the “+” plus sign on the main page of the software.


It can be configured according to the picture above,

  1. You can fill in any English name you like
  2. Client ID is ignored by default
  3. Server address: broker.emqx.io
  4. Port: 1883
  5. Username: emqx
  6. Password: public
  7. Other parameters can be configured as shown in the picture.
    After filling in the configuration, click Connect

Add subscription



Add a subscription with the theme TEST/DHT11, fill it in and click OK.

After the interface is as shown above, the subscription has been added, and the subscription topic above can be changed by yourself.
At this point, MQTT X is configured and “set aside for later use”.

ESP32 driver DHT11

Since the main purpose of this article is to upload DHT11 data to the MQTT server, the DHT11 driver will not be elaborated in detail. Instead, we will directly call the “DHT Sensor Library For ESPx” library and create a single order to learn about this library. First implement ESP32 to drive DHT11 and print out the temperature and humidity from the serial port.
The following is the driver code written by calling the “DHT Sensor Library For ESPx” library

#include <Arduino.h>
#include "DHTesp.h"

/**Initialize DHT sensor 1 */
DHTespdht;

int dhtPin = 5;

/** Data from sensor 1 */
TempAndHumidity dhtData;

void setup() {<!-- -->
Serial.begin(115200);
  
//Initialize temperature sensor 1
dht.setup(dhtPin, DHTesp::DHT11);

}

void loop() {<!-- -->
  dhtData = dht.getTempAndHumidity(); // Read values from sensor 1
Serial.println("Temp: " + String(dhtData.temperature,2) + "'C Humidity: " + String(dhtData.humidity,1) + "%");
  delay(1000);

}

Output results

ESP32 sends data to MQTT server

In this experiment, the two libraries “PubSubClient” and “WiFi” are used to communicate between ESP32 and the MQTT server.
For the wifi and MQTT parameters defined in the code, code transplantation requires modifying your own WIFI parameters and MQTT parameters.

const char *ssid="xxxxxxxx"; //WIFI name
const char *password="xxxxxxxx"; //WIFI password

const char *mqtt_broker = "xxxxxxxx"; //MQTT address
const char *topic = "xxxxxxxx"; //MQTT topic
const char *mqtt_username = "xxxxxxxx"; //MQTT username
const char *mqtt_password = "xxxxxxxx"; //MQTT user password
const int mqtt_port = xxxxxxxx; //MQTT port

With the wifi name and password defined above, use the following WIFI initialization statement to connect ESP32 to WIFI.

 WiFi.begin(ssid,password);

The setServer and connect functions in the “PubSubClient” library connect to the MQTT server by entering the MQTT server address, port number and user account

client.setServer(mqtt_broker,mqtt_port); //MQTT address, port number
client.connect(client_id.c_str(),mqtt_username,mqtt_password);

Subscribe to topic

client.subscribe(topic); //Subscribe to the topic

Then send data to the topic responded by the MQTT server through the publish function.

client.publish(topic,"I AM ESP32");

To the “TEST/DHT11” topic of the MQTT server

The connection is successful and “I AM ESP32” is uploaded to the topic “TEST/DHT11” of the MQTT server.

#include <WiFi.h>
#include <PubSubClient.h>

//WIFI parameter configuration
const char *ssid="JS-TEST";
const char *password="YXDZ@2022";

//MQTT parameter configuration
const char *mqtt_broker = "broker.emqx.io"; //MQTT address
const char *topic = "TEST/DHT11"; //MQTT topic
const char *mqtt_username = "emqx"; //MQTT username
const char *mqtt_password = "public"; //MQTT user password
const int mqtt_port = 1883; //MQTT port

WiFiClient espClient; //Create WIFI object
PubSubClient client(espClient);


void setup() {<!-- -->
  // put your setup code here, to run once:
  //Initialize serial port
  Serial.begin(115200);
  //Initialize wifi, connect to wifi
  WiFi.begin(ssid,password);
  //Check whether it is connected to wifi. If it is not connected, it will loop continuously. If it is connected, it will continue to run.
  while(WiFi.status()!=WL_CONNECTED)
  {<!-- -->
    delay(500);
    Serial.println("Connecting to WIFI ...");
    }
    Serial.println("Connecting to WIFI network");
    //Connect to MQTT server
    client.setServer(mqtt_broker,mqtt_port); //MQTT address, port number
    //Enter the loop and start connecting to the MQTT server. Once connected, exit the loop. If not connected, the loop will continue to connect.
    while(!client.connected())//Determine whether to connect to the MQTT server
    {<!-- -->
      //client_id assignment plus device mac
      String client_id = "esp32-client-";
      client_id + =String(WiFi.macAddress());
      Serial.printf("the client %s connects to public mqtt broker\\
",client_id.c_str());
      if(client.connect(client_id.c_str(),mqtt_username,mqtt_password)) //Connect to MQTT server
      {<!-- -->
        Serial.println("Public emqx mqtt broker connected"); //Connection successful, print information
        }
        else
        {<!-- -->
          Serial.print("failed with state"); //Connection failed
          Serial.print(client.state()); //Reconnect
          delay(2000);
          }
      }

  client.publish(topic,"I AM ESP32"); //Send information to the MQTT server
  client.subscribe(topic); //Subscribe to the topic
}


void loop() {<!-- -->
  // put your main code here, to run repeatedly:
  client.loop();
}

MQTT reception
“TEST/DHT11” This topic received “I AM ESP32” and the serial port returned “Public emqx mqtt broker connected” indicating that the MQTT server was successfully connected.
Next, upload the temperature and humidity data of DHT11 to the topic “TEST/DHT11”.

Upload temperature and humidity data

The above has completed the program for EPS32 to drive DHT11 and also completed the program for ESP32 to send data to the MQTT server. Uploading DHT11 data to the MQTT server is equivalent to integrating the two programs.
Since it is a free developed MQTT server, you need to pay attention to the frequency of uploading data. If you frequently upload data to the server, it may be disabled. So the data is uploaded here every 10 seconds.
Integrated code

#include <Arduino.h>
#include "DHTesp.h"
#include <WiFi.h>
#include <PubSubClient.h>

DHTespdht11;
int dhtPin = 5;
TempAndHumidity sensorData;

//WIFI parameter configuration
const char *ssid="JS-TEST";
const char *password="YXDZ@2022";

//MQTT parameter configuration
const char *mqtt_broker = "broker.emqx.io"; //MQTT address
const char *topic = "TEST/DHT11"; //MQTT topic
const char *mqtt_username = "emqx"; //MQTT username
const char *mqtt_password = "public"; //MQTT user password
const int mqtt_port = 1883; //MQTT port


WiFiClient espClient; //Create WIFI object
PubSubClient client(espClient);



void setup() {<!-- -->
  // put your setup code here, to run once:
  //Initialize serial port
  Serial.begin(115200);
  //Initialize DHT11
  dht11.setup(dhtPin, DHTesp::DHT11);
  //Initialize wifi, connect to wifi
  WiFi.begin(ssid,password);
  //Check whether it is connected to wifi. If it is not connected, it will loop continuously. If it is connected, it will continue to run.
  while(WiFi.status()!=WL_CONNECTED)
  {<!-- -->
    delay(500);
    Serial.println("Connecting to WIFI ...");
    }
    Serial.println("Connecting to WIFI network");
    //Connect to MQTT server
    client.setServer(mqtt_broker,mqtt_port); //MQTT address, port number
    client.setCallback(callback); //Connection return information
    //Enter the loop and start connecting to the MQTT server. Once connected, exit the loop. If not connected, the loop will continue to connect.
    while(!client.connected())//Determine whether to connect to the MQTT server
    {<!-- -->
      //client_id assignment plus device mac
      String client_id = "esp32-client-";
      client_id + =String(WiFi.macAddress());
      Serial.printf("the client %s connects to public mqtt broker\\
",client_id.c_str());
      if(client.connect(client_id.c_str(),mqtt_username,mqtt_password)) //Connect to MQTT server
      {<!-- -->
        Serial.println("Public emqx mqtt broker connected"); //Connection successful, print information
        }
        else
        {<!-- -->
          Serial.print("failed with state"); //Connection failed
          Serial.print(client.state()); //Reconnect
          delay(2000);
          }
      }

  client.publish(topic,"ESP32_HDT11"); //Send information to the MQTT server
  client.subscribe(topic); //Subscribe to the topic
}


void callback(char *topic, byte *payload, unsigned int length)
{<!-- -->
  Serial.print("Message arrived in topic:");
  Serial.println(topic); //Print topic name
  Serial.print("message:");zhuyi
  //Print the information returned by MQTT
  for(int i=0;i<length;i + + )
  {<!-- -->
    Serial.print((char)payload[i]);
    }
  Serial.println();
  Serial.println("--------------------");
  
  
  }


void loop() {<!-- -->
  // put your main code here, to run repeatedly:
 // client.loop();
 
  sensorData = dht11.getTempAndHumidity();
  Serial.println("Temp: " + String(sensorData.temperature,2) + "'C Humidity: " + String(sensorData.humidity,1) + "%");
  client.publish(topic,(("Temp: " + String(sensorData.temperature,2) + "'C Humidity: " + String(sensorData.humidity,1) + "%"). c_str())); //Send information to MQTT server
  delay(10000);

}

Experimental results


From the picture above, you can see that after the Arduino IDE’s serial port is opened, the data is synchronously sent to the topic “TEST/DHT11”. Experiment completed.