ESP32 module comes with multiple inbuilt features and peripheral interfacing capability is one of those features. ESP32 module also consists of an inbuilt temperature sensor, but that can only measure the temperature of the ESP32 core not the temperature of the surrounding environment. So it is required to use a peripheral sensor to measure the temperature of the surrounding environment like home, garden, office etc.
Hello readers. I hope you all are doing great. In this tutorial, we will learn how to interface DHT11 (temperature and humidity sensor) with the ESP32. Later in this tutorial, we will discuss how to share the sensor readings obtained from the DHT11 sensor to a web server.
Before moving towards the interfacing and programming part, let’s have a short introduction to the DHT11 sensor, its working and its connections.
Where To Buy? | ||||
---|---|---|---|---|
No. | Components | Distributor | Link To Buy | |
1 | ESP32 | Amazon | Buy Now |
Fig. 1: DHT11 sensor
DHT11 is used to measure humidity and temperature from its surrounding. It monitors the ambient temperature and humidity of a given area. It consists of an NTC (negative temperature co-efficient) temperature sensor and a resistive type humidity sensor. It also consists of an 8-bit microcontroller. The microcontroller is responsible for performing ADC (analog to digital conversion) and provides a digital output over the single wire protocol.
DHT11 sensor can measure humidity from 20% to 90% with +-5% (RH or relative humidity) of accuracy and can measure the temperature in the range of 0 degrees Celsius to 50 degrees Celsius with +-2C of accuracy.
DHT11 sensors can also be used to implement a wired sensor system using a cable length of up to 20 meters.
There are two DHT modules (DHT11 and DHT22) available in the market to measure temperature and humidity. The purpose of both module are same but with different specifications. Like DHT22 sensor provides broader temperature and humidity sensitivity ranges. But DHT22 is costlier than DHT11. So you can prefer to use any of the module, as per your requirements.
Table: 1
Note: Connect a 10K resistor between data and power (+5V) pin of DHT11 sensor module.
Fig. 2: ESP32 and DHT11 connections/wiring
We are using Arduino IDE to compile and upload code into ESP32 module. To know more about Arduino IDE and how to use it, follow our previous tutorial i.e., on ESP32 programming series. Link is given below:
https://www.theengineeringprojects.com/2021/11/introduction-to-esp32-programming-series.html
DHT11 sensor uses single wire protocol to communicate data which requires a precise timing. In order to interface DHT11 sensor with ESP32 module it is required to add necessary libraries. To install the DHT11 sensor library;
Fig. 3: manage libraries
Fig. 4: Install DHT sensor library
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println(F("DHT test string!"));
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F("Humidity(%): "));
Serial.println(h);
Serial.print(F("Temp.: "));
Serial.print(t);
Serial.println(F("°C "));
Serial.print(F("Temp.: "));
Serial.print(f);
Serial.println(F("°F "));
Serial.print(F("Heat index: "));
Serial.println(hic);
Serial.println(" ");
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));
}
Fig. 5: Add necessary libraries
Fig. 6: Global declarations
Fig. 7
Fig. 9
Fig. 10
Fig. 11
Fig. 12: Heat index
Fig. ESP32 and DHT11 interfacing
Fig. 13: Readings observed from DHT11 sensor
The IoT is the interconnection of physical objects or devices with sensors and software accessing capabilities to communicate data or information over the internet.
To build an IoT network, we need an interface medium that can fetch, control, and communicate data between sender and receiver electronics devices or servers.
Espressif Systems created the ESP32 Wi-Fi chip series. The ESP32 module is equipped with a 32-bit Tensilica microcontroller, 2.4GHz Wi-Fi connectivity, an antenna, memory, and power management modules, and much more. All of these built-in features of this ESP32 module make it ideal for IoT applications.
It is an open data platform for the Internet of Things (Internet of Things). ThingSpeak is a MathWorks web service that allows us to send sensor readings/data to the cloud. We can also visualise and act on the data (calculate the data) sent to ThingSpeak by the devices. Data can be stored in both private and public channels.
ThingSpeak is commonly used for internet of things prototyping and proof of concept systems requiring analytics.
Fig. 14: Getting started for free
Fig. 15: Create new account
Fig. 16: MathWorks Sign in
Fig. 17: New Channel
Fig. 18: Fill the channel details
Fig. 19: Field Chart Edit
https://github.com/mathworks/thingspeak-arduino
Fig. 20: Adding ThingSpeak library
To check whether the library is successfully added or not:
Fig. 21: manage libraries
Fig. 22: Arduino IDE Library manager.
//------style guard ----
#ifdef __cplusplus
extern "C" {
#endif
uint8_t temprature_sens_read();
#ifdef __cplusplus
}
#endif
uint8_t temprature_sens_read();
// ------header files----
#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"
//-----netwrok credentials
char* ssid = "replace this with your SSID"; //enter SSID
char* passphrase = "replace this with your password"; // enter the password
WiFiServer server(80);
WiFiClient client;
//-----ThingSpeak channel details
unsigned long myChannelNumber = 3;
const char * myWriteAPIKey = "replace this with your API key";
//----- Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 1000;
//----DHT declarations
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
// Initializing the DHT11 sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
Serial.begin(115200); //Initialize serial
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, passphrase);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
//----nitialize dht11
dht.begin();
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop()
{
if ((millis() - lastTime) > timerDelay)
{
delay(2500);
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print("Temperature (ºC): ");
Serial.print(t);
Serial.println("ºC");
Serial.print("Humidity");
Serial.println(h);
ThingSpeak.setField(1, h);
ThingSpeak.setField(2, t);
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeFields(myChannelNumber,
myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
lastTime = millis();
}
}
Fig. 23: Libraries
Fig. 24
Fig. 25: server port
Fig. 26
Fig. 29
Fig. 30: connect to wifi
Fig.31: Fetch and print IP address
Fig. 32
Fig. 33
Fig. 34
Fig. 35
Fig. 36: Displaying humidity on thingSpeak server
Fig. 37: Displaying Temperature on ThingSpeak server
This concludes the tutorial. I hope you found this of some help and also hope to see you soon with new tutorial on ESP32.