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
| 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!
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!"); } }
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 |
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!
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);
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.
- 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.