#include <RTClib.h> // Include the RTClib library for RTC functionality
RTC_DS3231 rtc; // Create an RTC_DS3231 object
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
// Check if the RTC module is connected and working
if (!rtc.begin()) {
Serial.println("Couldn't find RTC. Please check wiring.");
while (1); // Halt if RTC is not found
}
// If the RTC lost power, set the time to the compilation time
if (rtc.lostPower()) {
Serial.println("RTC lost power, setting time to compilation time!");
rtc.adjust(DateTime(__DATE__, __TIME__));
}
}
void loop() {
DateTime now = rtc.now(); // Get the current date and time from the RTC
// Print the time to the Serial Monitor
Serial.print("Time: ");
// Format hours, minutes, and seconds with leading zeros
if (now.hour() < 10) Serial.print("0");
Serial.print(now.hour());
Serial.print(":");
if (now.minute() < 10) Serial.print("0");
Serial.print(now.minute());
Serial.print(":");
if (now.second() < 10) Serial.print("0");
Serial.print(now.second());
// Print the date to the Serial Monitor
Serial.print(" Date: ");
// Format day, month, and year with leading zeros
if (now.day() < 10) Serial.print("0");
Serial.print(now.day());
Serial.print("-");
if (now.month() < 10) Serial.print("0");
Serial.print(now.month());
Serial.print("-");
Serial.println(now.year());
delay(1000); // Wait for one second before updating the time again
}