/**
ESP32 + DHT22 Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
*/
#include "DHTesp.h"
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x3F or 0x27 16 column and 2 rows
const int DHT_PIN = 15;
#define fan 4 // ESP32 pin connected to relay
#define TEMP_UPPER_THRESHOLD 30 // upper temperature threshold
#define TEMP_LOWER_THRESHOLD 15 // lower temperature threshold
DHTesp dhtSensor;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// dht_sensor.begin(); // initialize the DHT sensor
lcd.init(); // initialize the lcd
lcd.backlight(); // open the backlight
pinMode(fan, OUTPUT);
}
void loop() {
lcd.clear();
lcd.setCursor(0, 0);
// float temperature = dht_sensor.readTemperature();; // read temperature in Celsius
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float humi = dhtSensor.getHumidity(); // read humidity
float tempC = dhtSensor.getTemperature(); // read temperature
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
lcd.print("Temp: ");
lcd.print(tempC); // display the temperature
lcd.print(" C");
lcd.setCursor(0, 1); // display position
lcd.print("Humi: ");
lcd.print(humi); // display the humidity
lcd.print(" %");
delay(1000);
if (isnan(tempC)) {
Serial.println("Failed to read from DHT sensor!");
} else {
if (tempC > TEMP_UPPER_THRESHOLD) {
Serial.println("Turn the fan on");
digitalWrite(fan, HIGH); // turn on
} else if (tempC < TEMP_LOWER_THRESHOLD) {
Serial.println("Turn the fan off");
digitalWrite(fan, LOW); // turn off
}
}
}