#include <Wire.h>
#include <RTClib.h>
#include <LiquidCrystal_I2C.h>
// Initialize RTC and LCD
RTC_DS3231 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change 0x27 if your I2C address is different
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Initialize the LCD with the correct columns and rows
lcd.begin(16, 2);
lcd.backlight(); // Turn on the LCD backlight
// Print a message to ensure LCD is working
lcd.setCursor(0, 0);
lcd.print("Initializing...");
// Initialize the RTC
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("RTC Not Found");
while (1); // Halt if RTC is not found
}
// Set RTC time if it lost power
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set to compile time
}
// Clear the LCD and set the header
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Time:");
}
void loop() {
// Get the current time from the RTC
DateTime now = rtc.now();
// Format time as HH:MM:SS
char timeStr[9]; // "HH:MM:SS"
snprintf(timeStr, sizeof(timeStr), "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
// Print the formatted time to the serial monitor (for debugging)
Serial.println(timeStr);
// Display time on the LCD
lcd.setCursor(0, 1); // Move to the second row, first column
lcd.print(timeStr); // Print the time
lcd.display(); // Ensure the display is updated
delay(1000); // Update every second
}