Bird
0
0
Arduinoprogramming~5 mins

Humidity and temperature (DHT11/DHT22) in Arduino

Choose your learning style9 modes available
Introduction

We use DHT11 or DHT22 sensors to measure the air's humidity and temperature. This helps us understand the environment around us.

To check the temperature and humidity inside a room for comfort.
To monitor weather conditions in a small weather station project.
To control a fan or heater based on temperature and humidity levels.
To log environmental data for plants in a garden or greenhouse.
Syntax
Arduino
#include <DHT.h>

#define DHTPIN 2     // Pin where the sensor is connected
#define DHTTYPE DHT11   // DHT11 or DHT22

DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

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

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" *C");

  delay(2000);
}

Use #define DHTTYPE DHT11 for DHT11 sensor or DHT22 for DHT22 sensor.

Always check if the sensor reading is valid using isnan() before using the values.

Examples
This sets the sensor type to DHT22 instead of DHT11.
Arduino
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
Reads temperature in Fahrenheit by passing true to readTemperature().
Arduino
float temperature = dht.readTemperature(true);
Checks if humidity reading failed and prints an error message.
Arduino
float humidity = dht.readHumidity();
if (isnan(humidity)) {
  Serial.println("Error reading humidity");
}
Sample Program

This program reads humidity and temperature from a DHT11 sensor connected to pin 2. It prints the values every 2 seconds. If the sensor fails to read, it shows an error message.

Arduino
#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    delay(2000);
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" *C");

  delay(2000);
}
OutputSuccess
Important Notes

Make sure to install the DHT sensor library in the Arduino IDE before running the code.

Use a pull-up resistor (usually 10k ohms) between the data pin and 5V for stable sensor readings.

The DHT11 sensor is less accurate and slower than DHT22 but cheaper.

Summary

DHT11 and DHT22 sensors measure humidity and temperature.

Use the DHT library to read sensor data easily.

Always check if readings are valid before using them.