#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD I2C control
#include "DHT.h" // Library for DHT22 sensor
#include <RTClib.h> // Library for DS1307 RTC
#define DHTPIN 13 // Define the pin for the DHT22 sensor (connected to pin 13)
#define DHTTYPE DHT22 // Define the type of DHT sensor (DHT22)
DHT dht(DHTPIN, DHTTYPE); // Initialize the DHT sensor on pin 13 as a DHT22 type
// Set the I2C address for the LCD (0x27 is a common address for LCD2004 I2C displays)
LiquidCrystal_I2C lcd(0x27, 20, 4); // Initialize the LCD object with I2C address and dimensions (20x4)
RTC_DS1307 rtc; // Create an RTC object for DS1307
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
dht.begin(); // Initialize the DHT sensor
if (!rtc.begin()) { // Initialize the RTC
lcd.print("Couldn't find RTC"); // Error message if RTC is not found
while (1); // Stop the program if there's no RTC
}
if (!rtc.isrunning()) { // Check if the RTC is running
lcd.print("RTC is NOT running!"); // Display warning if RTC is not running
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set RTC to the time of code compilation
}
lcd.setCursor(0, 0); // Set cursor to the first line, first character (0, 0)
lcd.print("Initializing..."); // Print initial message on the LCD
delay(2000); // Wait for 2 seconds to show the message
}
void loop() {
DateTime now = rtc.now(); // Get the current date and time from the RTC
float humidity = dht.readHumidity(); // Read the humidity from the DHT22 sensor
float temperature = dht.readTemperature(); // Read the temperature from the DHT22 sensor
lcd.clear(); // Clear the display
// Display the date and time on the first line (convert year to B.E.)
lcd.setCursor(0, 0);
lcd.print(now.day(), DEC); // Print the day
lcd.print('/');
lcd.print(now.month(), DEC); // Print the month
lcd.print('/');
lcd.print(now.year() + 543, DEC); // Print the year in B.E. (พ.ศ.) by adding 543
lcd.print(" ");
lcd.print(now.hour(), DEC); // Print the hour
lcd.print(':');
lcd.print(now.minute(), DEC); // Print the minute
// Display the temperature and humidity on the second line
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temperature); // Print the temperature value
lcd.print(" C");
lcd.setCursor(0, 2);
lcd.print("Humidity: ");
lcd.print(humidity); // Print the humidity value
lcd.print(" %");
delay(2000); // Wait for 2 seconds before the next reading
}