Try Embedded

DHT22 weather station

Read temperature and humidity from a DHT22 and work out the "feels like" heat index.

Sensors · Beginner

In a real product: Greenhouse climate sensor (Agriculture): Temperature and humidity decide when to vent, heat or mist.

The DHT22 measures temperature and humidity and sends both digitally over a single wire. The DHT library handles its timing-sensitive protocol, so reading it takes two function calls.

What you'll learn

  • Using a digital sensor with its library (DHT sensor library)
  • Checking for a failed read with isnan()
  • Respecting a sensor's update rate (one reading every 2 seconds)

How it works

VCC and GND power the sensor and its data pin (SDA) goes to pin 2. To read it, the board pulls the line low for at least 1 ms; the sensor answers with 40 bits, each a short (0) or long (1) high pulse: humidity, temperature and a checksum.

dht.readHumidity() and dht.readTemperature() do all of that and return the values, or NaN (not a number) if the reply was missing or corrupt. computeHeatIndex() combines them into how hot it feels.

The data line needs a pull-up resistor (often 10 kΩ, built into many modules); the library also turns on the pin's internal pull-up.

Try this

  • Change the sensor's temperature and humidity sliders while it runs.
  • Show the readings on an LCD or OLED display.
  • Warn with an LED when the humidity goes above 70 %.

sketch.ino

// A DHT22 on pin 2: temperature, humidity and heat index every 2 seconds.
#include <DHT.h>

DHT dht(2, DHT22);

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

void loop() {
  delay(2000);  // the DHT22 updates at most every 2 seconds
  float humidity = dht.readHumidity();
  float celsius = dht.readTemperature();
  if (isnan(humidity) || isnan(celsius)) {
    Serial.println("Failed to read the DHT22");
    return;
  }
  float feelsLike = dht.computeHeatIndex(celsius, humidity, false);

  Serial.print("Temperature: ");
  Serial.print(celsius, 1);
  Serial.print(" C  Humidity: ");
  Serial.print(humidity, 1);
  Serial.print(" %  Feels like: ");
  Serial.print(feelsLike, 1);
  Serial.println(" C");
}

Lessons behind it