Arduino Real TIme Clock
#include <Wire.h>
#include <RTClib.h>
RTC_DS3231 rtc; // Create an instance of the RTC_DS3231 class
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
if (!rtc.begin()) { // Start communication with the RTC module
Serial.println("Couldn't find RTC");
while (1);
}
if (rtc.lostPower()) { // Check if the RTC lost power and if so, set the time
Serial.println("RTC lost power, setting the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // Set the RTC with the date and time of compiling
}
}
void loop() {
DateTime now = rtc.now(); // Get the current date and time from the RTC module
Serial.print(now.year(), DEC); // Print year
Serial.print('/');
Serial.print(now.month(), DEC); // Print month
Serial.print('/');
Serial.print(now.day(), DEC); // Print day
Serial.print(" ");
Serial.print(now.hour(), DEC); // Print hour
Serial.print(':');
Serial.print(now.minute(), DEC); // Print minute
Serial.print(':');
Serial.print(now.second(), DEC); // Print second
Serial.println();
delay(1000); // Delay for 1 second
}
This C++ code utilizes the RTClib library to interface with the DS3231 Real-Time Clock (RTC) module on an Arduino board. The code initializes the communication with the RTC, sets the current time if the RTC has lost power, and continuously reads the date and time from the RTC, displaying it over the serial monitor in a loop.