working-with-code-experiments

How to Measure Humidity and Temperature with DHT22 Sensor and Arduino

Difficulty Level: Beginner

Learn how to measure humidity and temperature using the DHT22 sensor and an Arduino. This easy-to-follow tutorial explains the wiring, code, and optional LCD integration to display real-time readings.

Components Required

Step 1: Wiring the Circuit

Follow these steps to connect the DHT22 sensor to the Arduino:

Step 2: Arduino Code


#include "DHT.h"

#define DHTPIN 2        // Pin where the DHT22 data pin is connected
#define DHTTYPE DHT22   // DHT 22 (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(9600);
    dht.begin();
    Serial.println("DHT22 sensor reading started");
}

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);
}
        

Optional: Display on LCD

To display the sensor readings on an LCD, use the code below:


#include 
#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

void setup() {
    lcd.begin(16, 2);
    dht.begin();
    lcd.print("DHT22 Sensor");
    delay(1000);
}

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

    if (isnan(humidity) || isnan(temperature)) {
        lcd.setCursor(0, 1);
        lcd.print("Sensor error");
        return;
    }

    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temperature);
    lcd.print(" C");

    lcd.setCursor(0, 1);
    lcd.print("Humidity: ");
    lcd.print(humidity);
    lcd.print(" %");

    delay(2000);
}
        

Step 3: Testing the DHT22 Sensor

Upload the code to your Arduino and open the Serial Monitor. You should see real-time temperature and humidity readings. If connected, the LCD will also display the sensor values.

Conclusion

By following this tutorial, you've successfully created a humidity and temperature monitoring system using the DHT22 sensor and Arduino. This project is ideal for weather stations, IoT applications, or home automation.

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!