OC
OceanRemote
Low-code IoT platform
← Back to Course

DHT22 Temperature and Humidity Sensor

DHT22 Temperature and Humidity Sensor

πŸŒ‘οΈπŸ’§ DHT22 Temperature and Humidity Sensor - Complete Guide

🌱 What You'll Learn in This Lesson:

  • 🌑️ Measure air temperature and humidity for crop health monitoring
  • πŸ’§ Calculate VPD (Vapor Pressure Deficit) for optimal plant growth
  • πŸ”Œ Wire DHT22 sensor correctly (digital communication)
  • πŸ’» Write complete Arduino/ESP32 code for environmental monitoring
  • πŸ“Š Send real-time data to OceanRemote cloud dashboard
  • 🌾 Automate greenhouse fans, misters, and heaters based on conditions
πŸ’‘ DHT22 vs DHT11: Which One for Your Farm?
Feature DHT22 (AM2302) DHT11
🌑️ Temperature Range -40°C to +80°C 0°C to +50°C
🎯 Temperature Accuracy ±0.5°C ±2°C
πŸ’§ Humidity Range 0-100% RH 20-90% RH
🎯 Humidity Accuracy ±2-5% RH ±5% RH
⏱️ Sampling Rate Every 2 seconds Every 1 second
πŸ’° Price $$ (higher) $ (budget)

Recommendation: Choose DHT22 for serious farming - better accuracy and wider range!

πŸ”Œ Complete Wiring Diagram

DHT22 Sensor Connections:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                                                                 β”‚
β”‚   DHT22 Sensor               ESP32/ESP8266                     β”‚
β”‚   ═══════════               ════════════                       β”‚
β”‚                                                                 β”‚
β”‚   Pin 1 (VCC)     ───► 3.3V or 5V (DHT22 works with both!)    β”‚
β”‚   Pin 2 (DATA)    ───► GPIO4                                   β”‚
β”‚   Pin 3 (NC)      ───► Not connected                           β”‚
β”‚   Pin 4 (GND)     ───► GND                                     β”‚
β”‚                                                                 β”‚
β”‚   IMPORTANT: Add a 10kΞ© resistor between DATA and VCC!         β”‚
β”‚                                                                 β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”                                                     β”‚
β”‚   β”‚       β”‚                                                     β”‚
β”‚   β”‚  10kΞ© β”‚                                                     β”‚
β”‚   β”‚       β”‚                                                     β”‚
β”‚   β””β”€β”€β”€β”¬β”€β”€β”€β”˜                                                     β”‚
β”‚       β”‚                                                         β”‚
β”‚    VCC┼───────────────────► Pin 1 (VCC)                        β”‚
β”‚       β”‚                                                         β”‚
β”‚       β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Ί Pin 2 (DATA) with pull-up          β”‚
β”‚       β”‚                                                         β”‚
β”‚    GND┼───────────────────► Pin 4 (GND)                        β”‚
β”‚                                                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Alternative: Many DHT22 modules include the 10kΞ© resistor already!
    
⚠️ CRITICAL: 2 Second Rule!

DHT22 requires AT LEAST 2 seconds between readings. Reading faster will return garbage data or cause sensor to freeze. Always use delay(2000) or more!

πŸ“š Required Libraries

Install the DHT sensor library in Arduino IDE:

1. "DHT sensor library" by Adafruit
2. "Adafruit Unified Sensor" by Adafruit

Install via: Sketch β†’ Include Library β†’ Manage Libraries β†’ Search "DHT22"
    

πŸ’» Basic Arduino Code (Single Sensor)

/*
 * DHT22 Temperature and Humidity Sensor - Basic Reading
 * Perfect for greenhouse, storage room, or weather monitoring
 * 
 * Components:
 * - 1x DHT22 sensor
 * - 1x 10kΞ© resistor (if not on module)
 * - ESP32/ESP8266 board
 */

#include 

// GPIO pin connected to DHT22 DATA wire
#define DHTPIN 4

// DHT22 sensor type
#define DHTTYPE DHT22

// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(115200);
    Serial.println("========================================");
    Serial.println("πŸŒ‘οΈπŸ’§ DHT22 Environmental Monitor v1.0");
    Serial.println("   Greenhouse Climate Station");
    Serial.println("========================================");
    
    dht.begin();
    delay(1000); // Give sensor time to stabilize
    Serial.println("βœ… DHT22 sensor initialized!");
}

void loop() {
    // Wait at least 2 seconds between readings!
    delay(2000);
    
    // Read temperature and humidity
    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature(); // Celsius
    
    // Check if readings are valid
    if (isnan(humidity) || isnan(temperature)) {
        Serial.println("❌ ERROR: Failed to read from DHT22 sensor!");
        Serial.println("   Check wiring and pull-up resistor!");
        return;
    }
    
    // Convert to Fahrenheit (optional)
    float tempF = temperature * 9.0 / 5.0 + 32.0;
    
    // Calculate Heat Index (apparent temperature)
    float heatIndex = dht.computeHeatIndex(temperature, humidity);
    float heatIndexF = dht.computeHeatIndex(tempF, humidity);
    
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    Serial.printf("🌑️ Temperature: %.1f°C | %.1f°F\n", temperature, tempF);
    Serial.printf("πŸ’§ Humidity: %.1f%%\n", humidity);
    Serial.printf("πŸ”₯ Heat Index: %.1fΒ°C | %.1fΒ°F\n", heatIndex, heatIndexF);
    
    // Crop recommendations based on conditions
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    Serial.println("πŸ“‹ CROP RECOMMENDATIONS:");
    
    if (temperature < 10) {
        Serial.println("⚠️ TOO COLD! Delay planting or use row covers");
    } else if (temperature >= 10 && temperature < 18) {
        Serial.println("🌱 Cool season: lettuce, spinach, kale, peas");
    } else if (temperature >= 18 && temperature < 28) {
        Serial.println("βœ… IDEAL for most vegetables! Plant anything");
    } else if (temperature >= 28 && temperature < 35) {
        Serial.println("🌞 Warm season: tomatoes, peppers, eggplant, corn");
    } else {
        Serial.println("⚠️ TOO HOT! Provide shade and increase ventilation");
    }
    
    if (humidity < 30) {
        Serial.println("πŸ’§ LOW HUMIDITY! Use misters or humidify");
    } else if (humidity >= 30 && humidity < 50) {
        Serial.println("βœ… Good humidity for most crops");
    } else if (humidity >= 50 && humidity < 70) {
        Serial.println("πŸ’š IDEAL humidity for tomatoes and peppers");
    } else if (humidity >= 70 && humidity < 85) {
        Serial.println("⚠️ HIGH HUMIDITY! Increase ventilation");
    } else {
        Serial.println("❌ DANGEROUS HUMIDITY! Mold risk - ventilate immediately!");
    }
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
}
    

🌿 VPD (Vapor Pressure Deficit) Calculator

πŸ“Š What is VPD? Vapor Pressure Deficit is the BEST indicator of plant transpiration. It tells you if your plants can breathe properly!

/*
 * DHT22 with VPD Calculation - Advanced Greenhouse Control
 * VPD (Vapor Pressure Deficit) is the #1 metric for plant health!
 * 
 * Optimal VPD ranges:
 * - Seedlings/Clones: 0.4-0.8 kPa
 * - Vegetative growth: 0.8-1.1 kPa  
 * - Flowering/Fruiting: 1.0-1.5 kPa
 * - Too high (>1.6): Plants close stomata (stress)
 * - Too low (<0.4): Mold and disease risk
 */

#include 

#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

// Calculate Vapor Pressure Deficit (kPa)
float calculateVPD(float temperature, float humidity) {
    // Saturation Vapor Pressure (kPa) using Tetens equation
    float es = 0.6108 * exp((17.27 * temperature) / (temperature + 237.3));
    
    // Actual Vapor Pressure (kPa)
    float ea = es * (humidity / 100.0);
    
    // Vapor Pressure Deficit (kPa)
    float vpd = es - ea;
    
    return vpd;
}

String getVPDRecommendation(float vpd, float temperature) {
    if (vpd < 0.4) {
        return "⚠️ LOW VPD: High mold risk! Increase ventilation and temperature";
    } else if (vpd >= 0.4 && vpd < 0.8) {
        return "βœ… IDEAL VPD: Seedlings and clones thrive!";
    } else if (vpd >= 0.8 && vpd < 1.1) {
        return "βœ… IDEAL VPD: Perfect for vegetative growth!";
    } else if (vpd >= 1.1 && vpd < 1.5) {
        return "βœ… IDEAL VPD: Optimal for flowering and fruiting!";
    } else if (vpd >= 1.5 && vpd < 1.8) {
        return "⚠️ HIGH VPD: Plants closing stomata. Increase humidity!";
    } else {
        return "❌ CRITICAL VPD: Plants cannot transpire! Add misters/humidifier NOW!";
    }
}

void setup() {
    Serial.begin(115200);
    dht.begin();
    delay(1000);
    
    Serial.println("========================================");
    Serial.println("🌿 Advanced Greenhouse Climate Control");
    Serial.println("   VPD (Vapor Pressure Deficit) Monitor");
    Serial.println("========================================");
    Serial.println("");
    Serial.println("πŸ“Š VPD Reference:");
    Serial.println("   Seedlings:    0.4-0.8 kPa");
    Serial.println("   Vegetative:   0.8-1.1 kPa");
    Serial.println("   Flowering:    1.0-1.5 kPa");
    Serial.println("========================================\n");
}

void loop() {
    delay(5000); // DHT22 needs 2 seconds minimum
    
    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();
    
    if (isnan(humidity) || isnan(temperature)) {
        Serial.println("❌ Sensor error!");
        return;
    }
    
    float vpd = calculateVPD(temperature, humidity);
    String recommendation = getVPDRecommendation(vpd, temperature);
    
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    Serial.printf("🌑️ Temperature: %.1f°C\n", temperature);
    Serial.printf("πŸ’§ Humidity: %.1f%%\n", humidity);
    Serial.printf("πŸ“Š VPD: %.2f kPa\n", vpd);
    Serial.printf("πŸ’š %s\n", recommendation.c_str());
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
    
    // Action triggers for automation!
    if (vpd > 1.5) {
        Serial.println("🚨 ACTION REQUIRED: Turn on misters/humidifier!");
    }
    if (vpd < 0.4) {
        Serial.println("🚨 ACTION REQUIRED: Turn on exhaust fans!");
    }
    if (temperature > 32) {
        Serial.println("🚨 ACTION REQUIRED: Open vents, turn on shade cloth!");
    }
    if (humidity > 85) {
        Serial.println("🚨 ACTION REQUIRED: Run dehumidifier or fans!");
    }
}
    
πŸ“– Real Farm Application - Tomato Greenhouse:

A commercial tomato farmer in Morocco installed DHT22 sensors throughout their greenhouse:

  • 🌑️ Problem: Inconsistent tomato quality and blossom end rot
  • πŸ”¬ Solution: 5 DHT22 sensors monitoring different zones
  • πŸ“Š Discovery: Night humidity was 95% (too high) causing mold
  • βœ… Action: Automated exhaust fans when humidity > 85%
  • πŸ“ˆ Result: 40% reduction in mold, 25% increase in Grade A tomatoes

"VPD monitoring changed everything. Our tomatoes are healthier and more consistent!" - Greenhouse Manager, Morocco

☁️ Send Data to OceanRemote Cloud

/*
 * DHT22 with OceanRemote Cloud Integration
 * Monitor greenhouse climate from anywhere!
 * Get alerts when conditions are suboptimal
 */

#include 
#include 
#include 
#include 

#define DHTPIN 4
#define DHTTYPE DHT22

// WiFi Configuration
const char* ssid = "YOUR_WIFI";
const char* password = "YOUR_PASSWORD";

// OceanRemote Configuration  
const char* token = "YOUR_DEVICE_TOKEN";
const char* apiEndpoint = "https://api.oceanremote.net/device/state";

DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(115200);
    dht.begin();
    
    // Connect to WiFi
    Serial.print("πŸ“‘ Connecting to WiFi");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nβœ… WiFi connected!");
    Serial.println("πŸŒ‘οΈπŸ’§ DHT22 Cloud Monitor Ready\n");
}

float calculateVPD(float temperature, float humidity) {
    float es = 0.6108 * exp((17.27 * temperature) / (temperature + 237.3));
    float ea = es * (humidity / 100.0);
    return es - ea;
}

void sendToCloud(float temp, float humidity, float vpd) {
    if (WiFi.status() != WL_CONNECTED) {
        Serial.println("❌ WiFi disconnected!");
        return;
    }
    
    HTTPClient http;
    http.begin(apiEndpoint);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    String data = "token=" + String(token);
    data += "&temperature=" + String(temp);
    data += "&humidity=" + String(humidity);
    data += "&vpd=" + String(vpd);
    data += "&sensor=dht22";
    
    int httpCode = http.POST(data);
    
    if (httpCode == 200) {
        Serial.println("βœ… Data sent to OceanRemote");
    } else {
        Serial.printf("❌ Upload failed: HTTP %d\n", httpCode);
    }
    
    http.end();
}

void loop() {
    delay(10000); // Send every 10 seconds
    
    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();
    
    if (isnan(humidity) || isnan(temperature)) {
        Serial.println("❌ Sensor read failed!");
        return;
    }
    
    float vpd = calculateVPD(temperature, humidity);
    
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    Serial.printf("πŸ“€ SENDING TO CLOUD:\n");
    Serial.printf("   🌑️ %.1f°C\n", temperature);
    Serial.printf("   πŸ’§ %.1f%%\n", humidity);
    Serial.printf("   πŸ“Š %.2f kPa\n", vpd);
    
    sendToCloud(temperature, humidity, vpd);
    
    // Alerts for critical conditions
    if (temperature > 35) {
        Serial.println("🚨 ALERT: Temperature CRITICAL!");
    }
    if (humidity > 85) {
        Serial.println("🚨 ALERT: Humidity CRITICAL - Mold risk!");
    }
    if (vpd > 1.6 || vpd < 0.4) {
        Serial.println("🚨 ALERT: VPD out of optimal range!");
    }
    
    Serial.println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
}
    

πŸ”§ Troubleshooting Common Issues

Problem Solution
❌ "Failed to read from DHT sensor" Check 10kΩ pull-up resistor between DATA and VCC
❌ Reading NaN or 0.0 Add delay(2000) between readings - DHT22 needs 2 seconds!
❌ Temperature stuck at -40°C Bad connection on DATA pin - check wiring
❌ Humidity reads 99% always Sensor damaged by moisture - replace or dry out
❌ Erratic readings Cable too long (max 20m) or electrical interference
πŸŽ‰ Congratulations!

You now have a professional greenhouse monitoring system!

  • βœ… Measure temperature and humidity accurately
  • βœ… Calculate VPD for optimal plant growth
  • βœ… Send real-time data to OceanRemote cloud
  • βœ… Make data-driven decisions for your crops

Next step: Add a relay to automate fans or misters based on VPD!

πŸ“š Quick Reference - DHT22 Commands:
dht.begin();                        // Initialize sensor
float temp = dht.readTemperature(); // Read Celsius
float tempF = dht.readTemperature(true); // Read Fahrenheit
float humidity = dht.readHumidity(); // Read humidity %
float heatIndex = dht.computeHeatIndex(temp, humidity); // Heat index

// IMPORTANT: Always wait 2 seconds between readings!
delay(2000);
🌿 Pro Tip - Sensor Placement:

Place DHT22 sensors at CANOPY LEVEL (same height as plant leaves), NOT on the ground! Ground-level readings can be 5-10Β°C different from where your plants actually are. Use a small stake or hang from a support wire.

πŸ’‘ Key Takeaways:
  • Apply these concepts directly to your farm or project.
  • Take notes on important details for the quiz.
  • Use the button below to track your progress.