Created
March 30, 2026 15:32
-
-
Save Anas-jaf/6cd79846af70f19b7563bce98f71c882 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Wire.h> | |
| #include <LiquidCrystal_I2C.h> | |
| #include "RTClib.h" | |
| // 1. Initialize the LCD (Address 0x27 is standard, 16 columns, 2 rows) | |
| // If your screen is blank, change 0x27 to 0x3F | |
| LiquidCrystal_I2C lcd(0x27, 16, 2); | |
| // 2. Initialize the RTC module | |
| RTC_DS3231 rtc; | |
| void setup() { | |
| // Start I2C communication | |
| Wire.begin(); | |
| // Start the LCD | |
| lcd.init(); | |
| lcd.backlight(); | |
| // Start the RTC | |
| if (!rtc.begin()) { | |
| lcd.print("RTC Not Found!"); | |
| while (1); // Halt if hardware is disconnected | |
| } | |
| // --- THE PRODUCTION GATEKEEPER --- | |
| // This checks if the RTC lost power (battery failure or first time use) | |
| if (rtc.lostPower()) { | |
| lcd.clear(); | |
| lcd.print("Setting Time..."); | |
| // Sets the RTC to the date & time this sketch was compiled | |
| rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); | |
| delay(2000); | |
| lcd.clear(); | |
| } | |
| // If rtc.lostPower() is false, the code skips the adjustment | |
| // and keeps the real-time running from the battery. | |
| } | |
| void loop() { | |
| // Get the current time from the RTC chip | |
| DateTime now = rtc.now(); | |
| // Display Date on Top Row (Line 0) | |
| lcd.setCursor(0, 0); | |
| lcd.print("Date: "); | |
| if (now.day() < 10) lcd.print('0'); | |
| lcd.print(now.day()); | |
| lcd.print('/'); | |
| if (now.month() < 10) lcd.print('0'); | |
| lcd.print(now.month()); | |
| lcd.print('/'); | |
| lcd.print(now.year()); | |
| // Display Time on Bottom Row (Line 1) | |
| lcd.setCursor(0, 1); | |
| lcd.print("Time: "); | |
| printDigits(now.hour()); | |
| lcd.print(':'); | |
| printDigits(now.minute()); | |
| lcd.print(':'); | |
| printDigits(now.second()); | |
| delay(1000); // Update the screen every 1 second | |
| } | |
| // Helper function to keep the layout clean (adds leading zeros) | |
| void printDigits(int digits) { | |
| if (digits < 10) { | |
| lcd.print('0'); | |
| } | |
| lcd.print(digits); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment