OC
OceanRemote
Low-code IoT platform
← Back to Course

Complete DHT22/BME280 Code Examples

Complete DHT22/BME280 Code Examples

💻 Complete DHT22 and BME280 Code - Temperature, Humidity & Pressure

💻 What You'll Learn:

  • 🌡️ Read temperature and humidity with DHT22 (5-minute code)
  • 📊 Add barometric pressure for weather forecasting with BME280
  • ⚠️ Get automatic alerts for heat, humidity, and pressure changes
  • 💰 Choose DHT22 ($5) or BME280 ($10) for your farm

📖 DHT22 Code (Temperature + Humidity)

#include <DHT.h>
#define DHTPIN 16
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
    float t = dht.readTemperature();
    float h = dht.readHumidity();
    
    if (!isnan(t) && !isnan(h)) {
        Serial.printf("🌡️ %.1f°C | 💧 %.0f%%\n", t, h);
        
        if (t > 35) Serial.println("⚠️ HEAT - Increase irrigation");
        if (h > 80) Serial.println("⚠️ HUMID - Fungus risk");
        if (h < 30) Serial.println("⚠️ DRY - Plant stress");
    }
    delay(5000);
}
    

📖 BME280 Code (Temp + Humidity + Pressure)

#include <Wire.h>
#include <Adafruit_BME280.h>

Adafruit_BME280 bme;
float lastPressure;

void setup() {
    Serial.begin(115200);
    Wire.begin();
    bme.begin(0x76);
    lastPressure = bme.readPressure() / 100.0F;
}

void loop() {
    float t = bme.readTemperature();
    float h = bme.readHumidity();
    float p = bme.readPressure() / 100.0F;
    float trend = p - lastPressure;
    
    Serial.printf("🌡️ %.1f°C | 💧 %.0f%% | 📊 %.0f hPa\n", t, h, p);
    
    if (trend > 2) Serial.println("☀️ Rising - Good weather ahead");
    if (trend < -2) Serial.println("🌧️ Falling - Rain likely!");
    
    lastPressure = p;
    delay(60000);
}
    
💡 Which Sensor to Choose?
  • DHT22 ($5): Temp + humidity only. Simple, great for greenhouses
  • BME280 ($10): Temp + humidity + pressure. Best for weather stations
  • BMP280 ($5): Temp + pressure only (no humidity). Budget option
⚠️ Common Issues:
  • DHT22 needs 2 seconds between readings → Use delay(2000) minimum
  • Add 10kΊ pull-up resistor between DATA and VCC on DHT22
  • BME280 defaults to address 0x76 (SDO to GND) or 0x77 (SDO to 3.3V)
🎯 Quick Reference:
  • 🌡️ DHT22: GPIO16 → Data, 10kΊ pull-up, delay(2000)
  • 📊 BME280: GPIO21(SDA), GPIO22(SCL), 3.3V power
  • ⚠️ Temp >35°C = heat stress → water more
  • 💧 Humidity >80% = fungus risk → ventilate
💡 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.