Learn how to measure temperature and humidity in your Arduino projects using DHT11 or DHT22 sensors.
The DHT11 and DHT22 are sensors that allow for simultaneous measurement of temperature and humidity. While the DHT11 is more affordable, the DHT22 offers better accuracy and a wider range of measurements.
Feature | DHT11 | DHT22 |
---|---|---|
Temperature Range | 0 to 50°C | -40 to 125°C |
Temperature Accuracy | ±2°C | ±0.5°C |
Humidity Range | 20 to 80% | 0 to 100% |
Humidity Accuracy | ±5% | ±2-5% |
Connect the sensor as follows:
The following code uses the Adafruit DHT library to read and display temperature and humidity data:
#include "DHT.h"
// Uncomment the sensor model you're using
//#define DHTTYPE DHT11
#define DHTTYPE DHT22
const int DHTPin = 5; // Sensor connected to digital pin 5
DHT dht(DHTPin, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx Test!");
dht.begin();
}
void loop() {
delay(2000); // Wait 2 seconds between measurements
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
}