OC
OceanRemote
Low-code IoT platform
โ† Back to Course

Complete Weather Station

Complete Weather Station

โ›… Complete Weather Station - Monitor Temperature & Humidity

๐ŸŒก๏ธ What You'll Learn in This Lesson:

  • Build a solar-powered weather station for your farm
  • Measure temperature and humidity with DHT22 sensor
  • Send real-time weather data to OceanRemote cloud
  • Optimize battery life with deep sleep (5-minute intervals)
  • Monitor crop conditions remotely from anywhere

๐Ÿ“‹ Why Weather Monitoring Matters for Your Farm

Weather conditions directly affect crop health, disease risk, and irrigation needs. With this weather station, you can:

Weather Parameter Why It Matters Actionable Insight
๐ŸŒก๏ธ Temperature Affects germination, growth, and flowering Protect crops when temperature exceeds 35ยฐC or drops below 5ยฐC
๐Ÿ’ง Humidity High humidity promotes fungal diseases Increase ventilation when humidity > 80%
๐ŸŒง๏ธ Rainfall (add later) Helps optimize irrigation scheduling Skip irrigation when rain is detected

๐Ÿ› ๏ธ Components You'll Need

Component Approximate Cost Purpose
ESP32 $5-10 Brain of the weather station
DHT22 Sensor $5-7 Measures temperature and humidity
10kฮฉ Resistor $0.10 Pull-up for DHT22 data line
6V Solar Panel (optional) $10-15 For off-grid operation

๐Ÿ”Œ Wiring Diagram

๐Ÿ“ Connection Instructions:
DHT22 Sensor โ†’ ESP32
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Pin 1 (VCC)  โ†’ 3.3V             โ”‚
โ”‚ Pin 2 (DATA) โ†’ GPIO16           โ”‚
โ”‚ Pin 3 (NC)   โ†’ Not connected    โ”‚
โ”‚ Pin 4 (GND)  โ†’ GND              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Add a 10kฮฉ resistor between DATA and VCC!

๐Ÿ“– Complete Code with Line-by-Line Explanation

/*
 * Complete Weather Station for ESP32
 * Monitors temperature and humidity using DHT22
 * Sends data to OceanRemote cloud every 5 minutes
 * Perfect for monitoring greenhouse or field conditions
 * 
 * Components Required:
 * - ESP32 board
 * - DHT22 temperature/humidity sensor
 * - 10kฮฉ resistor
 * - (Optional) Solar panel + battery for off-grid
 */

#include        // For internet connectivity
#include  // For sending data to cloud
#include         // DHT sensor library

// ========== DHT22 CONFIGURATION ==========
#define DHTPIN 16       // GPIO16 - Data pin for DHT22
#define DHTTYPE DHT22   // Using DHT22 sensor (more accurate than DHT11)

// ========== WIFI CONFIGURATION ==========
const char* ssid = "YOUR_WIFI";        // Replace with your WiFi name
const char* password = "YOUR_PASSWORD"; // Replace with your WiFi password

// ========== OCEANREMOTE CONFIGURATION ==========
const char* token = "YOUR_TOKEN";      // Replace with your OceanRemote device token

// Create DHT object
DHT dht(DHTPIN, DHTTYPE);

void setup() {
    // ---------- STEP 1: INITIALIZE SENSORS ----------
    Serial.begin(115200);
    dht.begin();  // Start the DHT22 sensor
    
    // ---------- STEP 2: CONNECT TO WIFI ----------
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nโœ… WiFi connected!");
    
    // ---------- STEP 3: READ SENSOR DATA ----------
    float temp = dht.readTemperature();  // Read temperature in Celsius
    float hum = dht.readHumidity();       // Read humidity percentage
    
    // Check if readings are valid (not NaN - Not a Number)
    if (!isnan(temp) && !isnan(hum)) {
        Serial.print("๐ŸŒก๏ธ Temperature: ");
        Serial.print(temp);
        Serial.println("ยฐC");
        Serial.print("๐Ÿ’ง Humidity: ");
        Serial.print(hum);
        Serial.println("%");
        
        // ---------- STEP 4: SEND DATA TO OCEANREMOTE ----------
        HTTPClient http;
        http.begin("https://api.oceanremote.net/device/state");
        http.addHeader("Content-Type", "application/x-www-form-urlencoded");
        
        // Build the data string
        String data = "token=" + String(token);
        data += "&temperature=" + String(temp);
        data += "&humidity=" + String(hum);
        
        // Send POST request
        int httpCode = http.POST(data);
        
        if (httpCode > 0) {
            Serial.println("โœ… Data sent to OceanRemote!");
        } else {
            Serial.println("โŒ Failed to send data");
        }
        
        http.end();  // Close connection
    } else {
        Serial.println("โŒ Failed to read from DHT22 sensor!");
    }
    
    // ---------- STEP 5: DEEP SLEEP (5 MINUTES) ----------
    // Sleep for 5 minutes to save power
    // Formula: minutes * 60 * 1,000,000 microseconds
    esp_sleep_enable_timer_wakeup(5 * 60 * 1000000ULL);
    Serial.println("๐Ÿ’ค Going to sleep for 5 minutes...");
    esp_deep_sleep_start();  // ESP32 goes to sleep here
}

void loop() {
    // This function never runs due to deep sleep
    // The ESP32 wakes up, runs setup(), then sleeps again
}
    

๐Ÿ“Š Code Breakdown: Understanding Each Part

๐Ÿ“ก 1. DHT22 Library and Initialization

#include 
#define DHTPIN 16
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
  • #include <DHT.h> - Includes the DHT sensor library (install via Arduino Library Manager)
  • #define DHTPIN 16 - Sets the GPIO pin connected to DHT22 data
  • #define DHTTYPE DHT22 - Tells the library we're using DHT22 (more accurate)
  • DHT dht(DHTPIN, DHTTYPE); - Creates a DHT object for reading data
  • dht.begin(); - Initializes the sensor in setup()

๐Ÿ“ก 2. Reading Temperature and Humidity

float temp = dht.readTemperature();  // Returns Celsius
float hum = dht.readHumidity();       // Returns percentage (0-100%)
  • dht.readTemperature() - Returns temperature in Celsius (add true for Fahrenheit: .readTemperature(true))
  • dht.readHumidity() - Returns relative humidity percentage
  • โš ๏ธ Important: These functions return NaN (Not a Number) if reading fails. Always check with !isnan()

๐Ÿ“ก 3. Sending Data to OceanRemote

HTTPClient http;
http.begin("https://api.oceanremote.net/device/state");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

String data = "token=" + String(token);
data += "&temperature=" + String(temp);
data += "&humidity=" + String(hum);

int httpCode = http.POST(data);
  • HTTPClient http; - Creates an HTTP client object
  • http.begin(URL) - Specifies the OceanRemote API endpoint
  • http.addHeader() - Tells the server we're sending form data
  • http.POST(data) - Sends the data and returns HTTP status code (200 = success)

๐Ÿ”‹ 4. Deep Sleep for Battery Life

esp_sleep_enable_timer_wakeup(5 * 60 * 1000000ULL);
esp_deep_sleep_start();
  • esp_sleep_enable_timer_wakeup() - Sets a timer to wake the ESP32
  • Formula: minutes ร— 60 ร— 1,000,000 (microseconds)
  • esp_deep_sleep_start() - Immediately puts ESP32 into deep sleep
  • Power consumption: 2.5ฮผA (microamps) during sleep!

๐ŸŽฏ Customizing Your Weather Station

Change Reading Interval

// Every 5 minutes (current)
esp_sleep_enable_timer_wakeup(5 * 60 * 1000000ULL);

// Every 1 minute (more frequent)
esp_sleep_enable_timer_wakeup(1 * 60 * 1000000ULL);

// Every 15 minutes (battery saving)
esp_sleep_enable_timer_wakeup(15 * 60 * 1000000ULL);

Use Fahrenheit Instead of Celsius

float temp = dht.readTemperature(true);  // true = Fahrenheit

Add Temperature Alerts

if (temp > 35) {
    Serial.println("โš ๏ธ HIGH TEMPERATURE! Open greenhouse vents!");
} else if (temp < 5) {
    Serial.println("โš ๏ธ LOW TEMPERATURE! Risk of frost!");
}

if (hum > 80) {
    Serial.println("โš ๏ธ HIGH HUMIDITY! Risk of fungal disease!");
}

๐Ÿ“ˆ DHT22 vs DHT11 Comparison

Feature DHT22 DHT11
Temperature Range -40ยฐC to +80ยฐC 0ยฐC to +50ยฐC
Temperature Accuracy ยฑ0.5ยฐC ยฑ2ยฐC
Humidity Range 0-100% 20-90%
Humidity Accuracy ยฑ2% ยฑ5%
๐Ÿ’ก Recommendation:

Use DHT22 for agriculture. The extra cost ($2-3 more) is worth it for accurate readings that help you make better farming decisions!

๐Ÿ“– Real-World Example - Moroccan Greenhouse:

A tomato farmer installed this weather station in a 500mยฒ greenhouse. Results:

  • ๐ŸŒก๏ธ Detected temperature spikes >40ยฐC โ†’ opened vents, saved crop
  • ๐Ÿ’ง Humidity alerts prevented fungal disease (reduced losses by 35%)
  • ๐Ÿ“Š Historical data helped optimize planting times for next season

"The weather station paid for itself in one season by preventing disease!" - Greenhouse Manager, Morocco

โš ๏ธ Common Issues & Troubleshooting:
  • โŒ "Failed to read from DHT22": Check wiring (add 10kฮฉ pull-up resistor between DATA and VCC)
  • โŒ NaN readings: DHT22 needs 2 seconds between readings. Add delay(2000) after dht.begin()
  • โŒ WiFi not connecting: Verify SSID/password and signal strength (ESP32 needs 2.4GHz WiFi)
  • โŒ Data not appearing in OceanRemote: Verify token is correct and device is activated
  • โŒ ESP32 not waking from sleep: Connect GPIO16 to RST pin for deep sleep wake-up

๐Ÿ”‹ Battery Life Calculation

With a 2000mAh battery and 5-minute wake intervals:

  • Wake time: 3 seconds @ 150mA = 0.125mAh per cycle
  • Sleep time: 5 minutes @ 0.0025mA = 0.00021mAh per cycle
  • Total per cycle: ~0.125mAh
  • Cycles per day: 288
  • Daily consumption: 36mAh
  • 2000mAh battery lasts: 2000 รท 36 = 55 DAYS
โ˜€๏ธ Solar Power Option:

Add a 6V 2W solar panel with a TP4056 charging module for unlimited battery life! The system will run indefinitely.

๐Ÿš€ Next Steps: Enhance Your Weather Station

  • Add a rain sensor: Detect rainfall and adjust irrigation schedules
  • Add a barometric pressure sensor (BMP280): Predict weather changes
  • Add an anemometer: Measure wind speed for spray timing
  • Add a light sensor (LDR): Track sunlight for photosynthesis monitoring
  • Connect to a display (OLED): Show real-time readings locally
๐ŸŽ‰ Congratulations!

You've built a complete, solar-ready weather station! Your farm can now monitor temperature and humidity remotely, helping you make better decisions about planting, harvesting, and disease prevention.

๐Ÿ“Š Check your data dashboard at OceanRemote to see temperature and humidity trends over time!

๐Ÿ’ก 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.