Sub topic 5
Installing the DHT Library and Declaring the Sensor
This chapter covers the software side of setting up a DHT11 or DHT22. It assumes you can write a basic sketch with setup() and loop(), upload it, and use the Serial Monitor. It also assumes the sensor is already wired: power, ground, a data pin, and a pull-up resistor on the data line. The chapter ends with a sketch that compiles and starts the sensor. Reading values is covered in the next chapter.
Why use a library
A DHT sensor sends its data over a single wire. The sensor expects a start signal from the Arduino, then answers with a stream of 40 bits. Each bit is encoded in how long the data line stays high. Decoding that stream means timing pulses within a few tens of microseconds, and interrupts or other code can disturb those timings.
A library hides this work. You create one object and call readTemperature() and readHumidity(). The library handles the start signal, the pulse timing, the checksum, and the conversion of raw bytes to numbers. The most common choice is the Adafruit DHT sensor library. It supports the DHT11, DHT21, and DHT22.
Installing the libraries
The Adafruit DHT library depends on a second library, Adafruit Unified Sensor. The DHT library includes a header from it, so the sketch will not compile without it.
With the Library Manager
- In the Arduino IDE, open Sketch > Include Library > Manage Libraries, or press the Library Manager icon in the sidebar.
- Search for
DHT sensor library. Choose the entry by Adafruit and click Install. - If the IDE asks whether to install dependencies, choose Install all. This adds Adafruit Unified Sensor.
- If it does not ask, search for
Adafruit Unified Sensorand install it yourself.
With arduino-cli
If you build from the command line, use these commands:
arduino-cli lib install "DHT sensor library"
arduino-cli lib install "Adafruit Unified Sensor"Check the installation
Open File > Examples > DHT sensor library > DHTtester. If the example is listed, the library is installed. Compile it for your board. A compile error that mentions Adafruit_Sensor.h means the dependency is missing.
Including the header and declaring the sensor
A sketch needs three things before it can talk to the sensor: the header, the pin number, and the sensor type.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);The parts of this declaration:
| Part | Meaning |
|---|---|
| `#include <DHT.h>` | Makes the `DHT` class and the type constants available. |
| `DHTPIN` | The Arduino digital pin connected to the sensor's data line. |
| `DHTTYPE` | One of `DHT11`, `DHT21`, or `DHT22`. These constants come from the library header. |
| `DHT dht(...)` | Creates the sensor object. The name `dht` is your choice. |
The declaration goes at global scope, outside setup() and loop(). Both functions need to use the same object, and a variable declared inside one function disappears when the function ends.
Choosing the type constant
The type tells the library how to interpret the raw bytes. The DHT11 and DHT22 format their numbers differently. The DHT11 sends whole numbers. The DHT22 sends values in tenths, and its temperature uses a sign bit for negative readings. If you pick the wrong type, the code still compiles and the sensor still answers, but the numbers are wrong.
| Sensor | Constant | Typical symptom of using the wrong one |
|---|---|---|
| DHT11 (blue case) | `DHT11` | Using `DHT22` shows values far too small, such as 2.4 instead of 24. |
| DHT22 / AM2302 (white case) | `DHT22` | Using `DHT11` shows values far too large or wildly wrong. |
A DHT22 sold on a small breakboard with three pins is usually an AM2302. It is the same chip and uses DHT22.
Choosing a pin
Any digital pin works for the data line. A few points help avoid trouble:
- Avoid pins 0 and 1 on an Uno. They are shared with the USB serial connection.
- Avoid pins used for upload or boot on other boards. On an ESP8266 or ESP32, some pins affect boot mode when held low or high.
- Keep the data wire short. Long wires add capacitance, which rounds the pulse edges and causes failed readings.
Why `#define` and `const`
The example uses #define because the official examples do. A typed constant does the same job and gives better compiler error messages:
const uint8_t DHT_PIN = 2;
DHT dht(DHT_PIN, DHT22);Both forms are valid. Whichever you choose, keep the pin and type at the top of the sketch so you change them in one place.
Starting the sensor in setup
Declaring the object does not configure the pin. You must call begin() in setup():
void setup() {
Serial.begin(9600);
dht.begin();
}begin() sets the data pin to input with the internal pull-up enabled and records the starting time. It does not talk to the sensor. The first real exchange happens when you call a read function.
The internal pull-up of an Arduino is weak, about 20 to 50 kΩ. The external pull-up resistor, usually 4.7 kΩ to 10 kΩ, is still needed for a stable signal. Many three-pin breakout boards already include that resistor. A bare four-pin sensor does not.
The object's life cycle
The following diagram shows the order of events from power-up to the first reading.
Three consequences follow from this order:
- Nothing is sent to the sensor until the first read call. A wrong pin or a missing sensor does not cause an error at
begin(). - The library works out the pulse timing from the CPU clock speed when it is compiled. You do not set it yourself.
- A DHT sensor needs about one second after power-up before it answers reliably. The DHT22 needs two seconds between reads. The sampling chapter covers this in detail.
A complete sketch that proves the setup
This sketch compiles, starts the sensor, and prints one value every two seconds. It includes only the minimum handling of a failed read, which a later chapter expands.
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("DHT setup check"));
dht.begin();
}
void loop() {
delay(2000);
float humidity = dht.readHumidity();
if (isnan(humidity)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.println(F(" %"));
}Open the Serial Monitor at 9600 baud. A plausible humidity value, typically between 20 and 80 percent indoors, confirms that the library, the wiring, and the type constant are all correct. Breathing on the sensor should raise the number within a few seconds.
Common errors at this stage
| Symptom | Likely cause | Fix |
|---|---|---|
| `DHT.h: No such file or directory` | The library is not installed, or the wrong board or sketchbook folder is in use. | Install the library with the Library Manager and restart the IDE. |
| `Adafruit_Sensor.h: No such file or directory` | Adafruit Unified Sensor is missing. | Install it. |
| `'DHT22' was not declared in this scope` | The `#include` is missing, or a different DHT library is installed. | Add `#include <DHT.h>` and remove conflicting libraries. |
| Compiles, but every read fails | Wrong pin, missing pull-up, loose wire, or a read interval below two seconds. | Check the pin number against the wiring, then check the resistor. |
| Values off by a factor of 10 | The type constant does not match the sensor. | Set `DHTTYPE` to match the case colour and model. |
| Works on an Uno, fails on a fast board | Timing sensitivity on a faster CPU. | Update the library, and try a different data pin. |
Optional: a third constructor argument
Older versions of the library took a third argument, a timing count, in the constructor. It was meant for fast processors. Current versions ignore it and calculate timing automatically, so you can leave it out. If you see DHT dht(DHTPIN, DHTTYPE, 15); in an old tutorial, it still compiles, but the third value no longer matters.
Exercise
A sketch using the Adafruit DHT library compiles without errors, and the sensor is wired correctly. It is a DHT11, but the code declares DHT dht(2, DHT22);. What do you expect to see, and what is the fix?
Show answer
The sketch compiles and the sensor responds, because the wiring and the protocol are the same for both models. The numbers come out wrong, because the DHT22 format treats the bytes as tenths and the DHT11 sends whole numbers. For example, a reading of 24 percent may appear as about 2.4 percent. The fix is to change the type constant to DHT11 in both the #define and the constructor call.
Exercise
Why must the DHT dht(DHTPIN, DHTTYPE); line be placed outside setup() and loop(), and why is dht.begin() still needed after the declaration?
Show answer
The object must be at global scope so that both setup() and loop() can use it. A variable declared inside a function is destroyed when that function returns. The constructor only stores the pin and type. begin() is the call that configures the pin as an input with its pull-up, so the sensor cannot be read correctly without it.