#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc;
void setup() {
Serial.begin(9600);
Wire.begin();
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) {
Serial.println("RTC lost power, let's set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
}
void loop() {
DateTime now = rtc.now();
printTime(now);
// Set your target time (HH:MM:SS)
int targetHours = 9;
int targetMinutes = 40;
int targetSeconds = 30;
// Calculate remaining time
int remainingSeconds = calculateRemainingTime(now, targetHours, targetMinutes, targetSeconds);
// Display the remaining time in HH:MM:SS format
Serial.print("Remaining Time: ");
printTimeRemaining(remainingSeconds);
delay(1000); // Wait for 1 second
}
void printTime(DateTime now) {
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
}
void printTimeRemaining(int seconds) {
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int remainingSeconds = seconds % 60;
// Print in HH:MM:SS format
if (hours < 10) Serial.print('0');
Serial.print(hours, DEC);
Serial.print(':');
if (minutes < 10) Serial.print('0');
Serial.print(minutes, DEC);
Serial.print(':');
if (remainingSeconds < 10) Serial.print('0');
Serial.println(remainingSeconds, DEC);
}
int calculateRemainingTime(DateTime now, int targetHours, int targetMinutes, int targetSeconds) {
int remainingSeconds = 0;
if (now.hour() < targetHours || (now.hour() == targetHours && now.minute() < targetMinutes) ||
(now.hour() == targetHours && now.minute() == targetMinutes && now.second() < targetSeconds)) {
remainingSeconds = ((targetHours * 3600 + targetMinutes * 60 + targetSeconds) -
(now.hour() * 3600 + now.minute() * 60 + now.second()));
}
if (remainingSeconds < 0) {
remainingSeconds = 0;
}
return remainingSeconds;
}