Sub topic 5
Installing the DHT Library and Declaring the Sensor
This chapter assumes you can create and upload an Arduino sketch, use the Serial Monitor, connect a breadboard circuit, and use basic C++ types such as float and int. You will set up the software object that represents a DHT11 or DHT22 sensor. Reading values comes in the next step.
Install the required libraries
The Adafruit DHT library provides the Arduino code for communicating with DHT sensors. It also uses the Adafruit Unified Sensor library for a common sensor interface.
Install both libraries through the Arduino IDE:
- Open Sketch > Include Library > Manage Libraries.
- Search for DHT sensor library.
- Select the library published by Adafruit and click Install.
- Search for Adafruit Unified Sensor.
- Select the library published by Adafruit and click Install.
The library name and the header name are different. In a sketch, include the library with:
#include <DHT.h>The Arduino IDE searches its installed library folders when it compiles this line. If the library is missing, compilation fails with an error such as DHT.h: No such file or directory.
Choose the sensor type
A DHT sensor is identified by both its data pin and its model. The DHTTYPE definition must match the physical sensor.
| Sensor | Arduino definition | Typical characteristic |
|---|---|---|
| DHT11 | `DHT11` | Lower cost, narrower measurement range |
| DHT22 | `DHT22` | Better resolution and wider range |
The sensor model does not usually appear in the code as a string. Instead, pass the library constant DHT11 or DHT22 to the constructor.
Declare the DHT object
A DHT object stores the configuration needed to communicate with one sensor. The constructor takes the Arduino pin connected to the sensor's data line and the sensor model.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
// Sensor-reading code will go here.
}DHTPIN is set to digital pin 2 in this example. Change it if your data wire uses another pin. DHTTYPE must match the installed sensor.
The declaration DHT dht(DHTPIN, DHTTYPE); creates a global object named dht. The object is available to both setup() and loop(). The statement dht.begin() initializes the library. Call it once from setup() before requesting measurements.
The Serial.begin(9600) line is not required by the DHT library itself. It prepares the Serial Monitor for messages that later code will print.
Exercise
Your sensor is a DHT11 connected to digital pin 7. Which two configuration lines should replace the example definitions?
Show answer
Use #define DHTPIN 7 and #define DHTTYPE DHT11.