#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
// Define pins for each component
#define DHTPIN 4
#define DHTTYPE DHT22
#define RED 16
#define BLUE 2
#define BUZZER 25
#define SERVO 19
// Define the highest range of temperature and humidity
#define highest_temp 30 // in Celsius
#define highest_humidity 70 // in percentage
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 4);
Servo ESP32Servo;
void setup() {
// Initialize components
dht.begin();
lcd.init();
lcd.backlight();
ESP32Servo.attach(SERVO);
pinMode(RED, OUTPUT);
pinMode(BLUE, OUTPUT);
pinMode(BUZZER, OUTPUT);
}
void loop() {
// Read temperature and humidity using the libraries of dht
float temp = dht.readTemperature();
float hum = dht.readHumidity();
//error handling for the sensor
if (isnan(temp) || isnan(hum)) {
lcd.setCursor(0, 0);
lcd.print("Sensor Error!");
delay(2000);
return;
}
//conditional statement to know if the temperature exceeded the limit set
if (temp >= highest_temp) {
digitalWrite(RED, HIGH);
} else {
digitalWrite(RED, LOW);
}
//conditional statement to know if the humidity exceeded the limit set
if (hum >= highest_humidity) {
digitalWrite(BLUE, HIGH);
} else {
digitalWrite(BLUE, LOW);
}
//condtion to know if it's time to open the exhaust fan
if (temp >= highest_temp && hum >= highest_humidity) {
digitalWrite(BUZZER, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("WARNING: HIGH T&H");
lcd.setCursor(0, 2);
lcd.print("Opening Exhaust");
ESP32Servo.write(0); // open exhaust fan
for (int i = 0; i < 5; i++) { // Blink 5 times
digitalWrite(RED, HIGH);
digitalWrite(BLUE, HIGH);
delay(300); // On for 300ms
digitalWrite(RED, LOW);
digitalWrite(BLUE, LOW);
delay(300); // Off for 300ms
}
delay(3000);
} else {
// Temperature or humidity is normal or have not reached the limit yet
digitalWrite(BUZZER, LOW);
ESP32Servo.write(90); //closed exhaust fan
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("T&H is now normal");
lcd.setCursor(0, 2);
lcd.print("Closing Exhaust");
delay(3000);
}
// Real-time display for the temperature and humidity
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temperature: ");
lcd.print(temp);
lcd.print("C");
lcd.setCursor(0, 2);
lcd.print("Humidity: ");
lcd.print(hum);
lcd.print("%");
delay(5000); // Refresh every 5 seconds
}