Sub topic 2
Installing the DHT Library and Declaring the Sensor
This chapter assumes you know the basic setup() and loop() structure of an Arduino sketch, can upload a sketch and open the Serial Monitor, and understand float and int types. Wire the sensor to pin 2 with a pull-up resistor before you start.
Installing the DHT library
The Adafruit DHT library handles the single-wire timing protocol for you.
- In the Arduino IDE, open Sketch > Include Library > Manage Libraries.
- Search for DHT sensor library by Adafruit and install it.
- When prompted, also install its dependency, Adafruit Unified Sensor.
Declaring the sensor
Add the header, define the data pin and sensor type, and create a sensor object at the top of the sketch. Then start the sensor in setup().
Reading temperature and humidity
Call readHumidity() and readTemperature() in loop(). Both return float values. The temperature is in Celsius by default.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);
float humidity = dht.readHumidity();
float temperatureC = dht.readTemperature();
if (isnan(humidity) || isnan(temperatureC)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F(" % Temperature: "));
Serial.print(temperatureC);
Serial.println(F(" C"));
}Detecting failed readings
A read can fail when the sensor is unplugged, miswired, or interrupted mid-transfer. In that case the library returns NaN (not a number). The isnan() function returns true for NaN. Check both values before you use them, because printing or calculating with NaN gives meaningless output.
Respecting the sampling interval
The DHT11 needs at least 1 second between reads. The DHT22 needs at least 2 seconds. Reading faster returns stale or failed values. The delay(2000) call at the top of loop() keeps the sketch within the DHT22 limit.
> Note: Using delay() blocks the whole sketch while it waits. Later chapters show how to read the sensor without blocking other work.
Exercise
The DHT22 has been replaced with a DHT11. What change keeps the sketch within the sensor's limit, and what is the minimum delay that the new value must respect?
Show answer
Change DHTTYPE to DHT11. Keep the delay at 2000 ms, or reduce it to any value of at least 1000 ms. The DHT11 needs at least 1 second between reads, so 2000 ms is safe.