Skip to content
SensorMITv1.4.6

DHT sensor library

by Adafruit

Adafruit's DHT sensor library handles the single-wire timing protocol used by the entire DHT family (DHT11, DHT21/AM2301, DHT22/AM2302), so you never have to bit-bang the read pulses yourself. Pass it a pin and a sensor type, and it gives you clean `readTemperature()` and `readHumidity()` calls that return `NAN` on a failed read instead of garbage data. It depends on Adafruit's "Adafruit Unified Sensor" library, which the Arduino Library Manager installs automatically alongside it. The same library and the same three function calls work across DHT11 and DHT22 — the only code change between the two is the `DHTTYPE` definition, which is what makes it easy to prototype on a cheap DHT11 and later swap in a more accurate DHT22 without rewriting anything.

Installation

Arduino IDE — Library Manager

Sketch → Include Library → Manage Libraries → search DHT sensor library

PlatformIO

lib_deps = adafruit/DHT sensor library

Supported boards

Arduino UnoESP32STM32 Blue Pill

Examples

Basic temperature & humidity read (DHT11)

Minimal setup for a DHT11 on pin 2 — the pattern every board integration on this site is built from.

#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  delay(2000);

  float humidity = dht.readHumidity();
  float tempC    = dht.readTemperature();

  if (isnan(humidity) || isnan(tempC)) {
    Serial.println(F("Failed to read from DHT sensor"));
    return;
  }

  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F(" %  Temp: "));
  Serial.print(tempC);
  Serial.println(F(" C"));
}

Swapping in a DHT22 for better accuracy

Identical code to the DHT11 example above — only the DHTTYPE define changes, which is the point of using this library across the DHT family.

#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT22   // was DHT11 - everything else stays the same

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  delay(2000);

  float humidity = dht.readHumidity();
  float tempC    = dht.readTemperature();

  if (isnan(humidity) || isnan(tempC)) {
    Serial.println(F("Failed to read from DHT sensor"));
    return;
  }

  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F(" %  Temp: "));
  Serial.print(tempC);
  Serial.println(F(" C"));
}

Computed heat index

The library can combine a temperature and humidity reading into a heat index ("feels like") value in one call, useful for weather-station style projects.

float tempC     = dht.readTemperature();
float humidity  = dht.readHumidity();
float heatIndex = dht.computeHeatIndex(tempC, humidity, false); // false = Celsius input/output

Serial.print(F("Heat index: "));
Serial.print(heatIndex);
Serial.println(F(" C"));