#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <RTClib.h>
// Initialize the LCD, adjust the I2C address (0x27 is common for LCD2004)
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Define DHT22 sensor settings
#define DHTPIN 13 // DHT22 data pin connected to GPIO 13
#define DHTTYPE DHT22 // DHT22 (AM2302) sensor type
DHT dht(DHTPIN, DHTTYPE);
// Initialize the DS1307 RTC
RTC_DS1307 rtc;
// Relay pin definitions
const int fanPin = 12; // Fan relay on pin 12
const int pumpPin = 14; // Pump relay on pin 14
const int lampPin = 27; // Lamp relay on pin 27
// Thresholds
const float tempThreshold = 30.0;
const float humThreshold = 80.0;
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
// Initialize DHT22 sensor
dht.begin();
// Initialize DS1307 RTC
if (!rtc.begin()) {
lcd.setCursor(0, 0);
lcd.print("Couldn't find RTC");
while (1); // Halt if RTC is not found
}
if (!rtc.isrunning()) {
lcd.setCursor(0, 0);
lcd.print("RTC is not running");
// Uncomment the next line to set the RTC to the current time
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
// Initialize relays
pinMode(fanPin, OUTPUT);
pinMode(pumpPin, OUTPUT);
pinMode(lampPin, OUTPUT);
// Ensure relays are off at start
digitalWrite(fanPin, HIGH); // Assume HIGH turns the relay off
digitalWrite(pumpPin, HIGH);
digitalWrite(lampPin, HIGH);
// Initial message
lcd.setCursor(0, 0);
lcd.print("Temp & Humidity");
delay(2000);
}
void loop() {
// Read temperature and humidity from DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any readings failed and exit early
if (isnan(humidity) || isnan(temperature)) {
lcd.setCursor(0, 0);
lcd.print("Error reading data");
return;
}
// Get current date and time from RTC
DateTime now = rtc.now();
// Display date and time on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(now.day(), DEC);
lcd.print('/');
lcd.print(now.month(), DEC);
lcd.print('/');
lcd.print(now.year(), DEC);
lcd.setCursor(0, 1);
lcd.print(now.hour(), DEC);
lcd.print(':');
lcd.print(now.minute(), DEC);
lcd.print(':');
lcd.print(now.second(), DEC);
// Display temperature on the third line
lcd.setCursor(0, 2);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
// Display humidity on the fourth line
lcd.setCursor(0, 3);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
// Control Fan based on temperature
if (temperature > tempThreshold) {
digitalWrite(fanPin, LOW); // Turn fan ON
} else {
digitalWrite(fanPin, HIGH); // Turn fan OFF
}
// Control Pump based on humidity
if (humidity < humThreshold) {
digitalWrite(pumpPin, LOW); // Turn pump ON
} else {
digitalWrite(pumpPin, HIGH); // Turn pump OFF
}
// (Optional) Control Lamp here if needed
// Wait before updating again
delay(2000);
}