â Back to Course
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.
×