#include "RTClib.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
RTC_DS3231 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Set a goal date, in this case 03/11/2023 23:00
DateTime goalDate = DateTime(2023, 11, 4, 17, 45, 0);
// Will store last time LCD was updated
unsigned long previousMillis = 0;
// interval at which to update LCD (milliseconds)
const long updateInterval = 1000;
void setup() {
Serial.begin(9600);
// Check if the RTC is connected
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
while (1) delay(10);
}
lcd.init();
lcd.clear();
}
void printTimeWithLeadingZero(LiquidCrystal_I2C &lcd, int value, int x, int y) {
lcd.setCursor(x, y);
if (value < 10) {
lcd.print("0");
}
lcd.print(value);
}
void loop() {
// Update currentMillis
unsigned long currentMillis = millis();
// Retrieve the current time
DateTime now = rtc.now();
// Check if updateInterval has elapsed since previousMillis
if (currentMillis - previousMillis >= updateInterval) {
// Save the last time you updated the LCD
previousMillis = currentMillis;
TimeSpan remainingTime = goalDate - now;
if (remainingTime.totalseconds() <= 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Goal time!");
} else {
int days = remainingTime.days();
int hours = remainingTime.hours();
int minutes = remainingTime.minutes();
int seconds = remainingTime.seconds();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Remaining time:");
// Ensure days are always displayed with three digits
lcd.setCursor(0, 1);
if (days < 100) lcd.print("0");
if (days < 10) lcd.print("0");
lcd.print(days);
lcd.print(" ");
printTimeWithLeadingZero(lcd, hours, 4, 1);
lcd.print(":");
printTimeWithLeadingZero(lcd, minutes, 7, 1);
lcd.print(":");
printTimeWithLeadingZero(lcd, seconds, 10, 1);
}
}
}