#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;
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__)));
}
// 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(" %");
// Wait before updating again
delay(2000);
}