How to use the DHT22 sensor with ESP8266?

posted Originally published at dev.to 9 min read

Hello, I'm Ganesh. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

In this article, I will be explaining how to use DHT22 sensor with ESP8266.

Setup Requirements

Most of use confuse with DHT11 and DHT22.

Both are temperature and humidity sensors. But they have different specifications.

DHT22 is more accurate than DHT11.

For visual identification, DT22 comes in white color while DHT11 comes in blue color.

Once this is correctly identified, and have a datasheet with us. We can proceed with the setup.

Integrate Using Pre-built Libraries.

Most of the sensor manufacturers provide libraries for their sensors. Also if they don't provide libraries, we can find libraries for them in the internet.

Mostly we can use arduino IDE for searching libraries.

Or

we can use platformio by just adding the library name in the lib_deps section of platformio.ini file.

PlatformIO Setup

Go to PlatformIO extension in VSCode.

Click on Create New Project.

  1. Give Project Name.

  2. Select the board in my case it was NodeMCU 1.0 (ESP-12E Module).

  3. Select Framework as Arduino.

You can see platformio.ini file with the following content:

; PlatformIO Project Configuration File
;
;   Build options: build flags, source filter
;   Upload options: custom upload port, speed and extra flags
;   Library options: dependencies, extra library storages
;   Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
; Common settings for both environments
; Common settings for both environments
[env]
platform = espressif8266
board = nodemcuv2
framework = arduino
monitor_speed = 115200

How to Code for DHT22 Sensor with ESP8266?

Now we setup project

Let's add library for DHT sensor.

lib_deps = 
    adafruit/DHT sensor library@^1.4.4

In the main code let's add the following code.

#include "DHT.h"

// Define the NodeMCU pin connected to the DHT22 data pin
#define DHTPIN D2     

// Define the sensor type
// If yours is DHT11, then change it to DHT11

#define DHTTYPE DHT22   

// Initialize the DHT sensor
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  // Start the serial communication
  Serial.begin(115200);
  Serial.println(F("DHT22 Sensor Test with NodeMCU!"));

  // Start the sensor
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  // The DHT22 requires about 2 seconds to stabilize between readings.
  delay(2000);

  // Read humidity
  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);

  // Print the results to the Serial Monitor
  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

In here we are setting up the DHT22 sensor with ESP8266.

Initialize DHT sensor.

Start DHT sensor.

Read humidity.

Read temperature.

Read heat index.

Print the results.

Compile and Connection of DHT22 with ESP8266

Now we can see tick mark in the bottom of the VSCode.

On clicking it we can verify the code is compiling.

Output 1:

Checking size .pio/build/sensor_node_1/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [===       ]  34.5% (used 28236 bytes from 81920 bytes)
Flash: [===       ]  26.3% (used 274819 bytes from 1044464 bytes)
======================================================================= [SUCCESS] Took 0.56 seconds =======================================================================

After compilation we can upload the code to the ESP8266 by clicking the upload button.

Now we can connect the vin pin of DHT22 to 3V3 pin of ESP8266 and gnd pin of DHT22 to gnd pin of ESP8266.
Data pin of DHT22 to D2 pin of ESP8266.

Uploading the code to ESP8266

Connect ESP8266 to the computer and click on arrow button.

Output 2:

Writing at 0x0002c000... (92 %)
Writing at 0x00030000... (100 %)
Wrote 278976 bytes (204732 compressed) at 0x00000000 in 18.0 seconds (effective 123.7 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

Finally we can see the output in the serial monitor on clicking socket button.

Output 3:

DHT22 Sensor Test with NodeMCU!
Humidity: 51.80%  Temperature: 31.30°C 88.34°F  Heat index: 33.51°C 92.31°F
Humidity: 51.80%  Temperature: 31.30°C 88.34°F  Heat index: 33.51°C 92.31°F
Humidity: 51.80%  Temperature: 31.30°C 88.34°F  Heat index: 33.51°C 92.31°F
Humidity: 51.70%  Temperature: 31.30°C 88.34°F  Heat index: 33.49°C 92.27°F

Conclusion

Now we could able to setup and test DHT22 sensor with ESP8266.

git-lrc

Any feedback or contributors are welcome! It’s online, source-available, and ready for anyone to use.
⭐ Star it on GitHub: https://github.com/HexmosTech/git-lrc

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

Breaking the AI Data Bottleneck: How Hammerspace's AI Data Platform Eliminates Migration Nightmares

Tom Smithverified - Mar 16

How to Connect a DHT11 to a NodeMCU v2 board?

Ganesh Kumar - Apr 14

What Do You Need to Know About the DHT22 Sensor Before Using It?

Ganesh Kumar - Mar 24

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9
chevron_left

Related Jobs

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!