#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <Servo.h>
// Pins
#define DHTPIN 2
#define DHTTYPE DHT22
#define SERVO_PIN 9
// Initialize components
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo ventServo;
void setup() {
Serial.begin(9600);
dht.begin();
lcd.init();
lcd.backlight();
ventServo.attach(SERVO_PIN);
// Booting Sequence
lcd.setCursor(0, 0);
lcd.print("GREENHOUSE CTRL");
lcd.setCursor(0, 1);
lcd.print("Booting Up... ");
ventServo.write(0); // Close window on start
delay(2000);
lcd.clear();
}
void loop() {
// 1. Read Climate Data
float humidity = dht.readHumidity();
float tempC = dht.readTemperature();
// Check if sensor reading failed
if (isnan(humidity) || isnan(tempC)) {
lcd.setCursor(0, 0);
lcd.print("Sensor Error! ");
return;
}
// 2. Display on LCD
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(tempC, 1); // 1 decimal point
lcd.print((char)223); // Degree symbol
lcd.print("C ");
lcd.setCursor(0, 1);
lcd.print("Humid: ");
lcd.print(humidity, 1);
lcd.print("% ");
// 3. Climate Logic (Actuation)
// If Temp > 30C, open the roof vent window!
if (tempC > 30.0) {
ventServo.write(90); // Open Window
lcd.setCursor(12, 0);
lcd.print("[OPN]");
} else {
ventServo.write(0); // Close Window
lcd.setCursor(12, 0);
lcd.print("[CLS]");
}
delay(1000); // Check environment every 1 second
}