#include <STM32RTC.h>
/* Get the RTC object */
STM32RTC& rtc = STM32RTC::getInstance();
void setup() {
Serial.begin(9600);
while (!Serial); // Wait for Serial monitor
// Select RTC clock source BEFORE rtc.begin()
rtc.setClockSource(STM32RTC::LSE_CLOCK); // Use external 32.768 kHz crystal (better accuracy)
rtc.begin(); // Start RTC in 24H format
// If RTC is not already set (first power-up), set it to compile time
if (!rtc.isTimeSet()) {
// Parse __DATE__ and __TIME__ (compile-time macros)
const char monthNames[12][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
char compileDate[] = __DATE__;
char compileTime[] = __TIME__;
int day, year, hour, minute, second;
char monthStr[4];
sscanf(compileDate, "%s %d %d", monthStr, &day, &year);
sscanf(compileTime, "%d:%d:%d", &hour, &minute, &second);
int month = 0;
for (int i = 0; i < 12; i++) {
if (strncmp(monthStr, monthNames[i], 3) == 0) {
month = i + 1;
break;
}
}
rtc.setTime(hour, minute, second);
rtc.setDate(1, day, month, year - 2000); // Weekday is dummy (1 = Monday)
}
Serial.println("RTC Initialized");
}
void loop() {
// Read current date and time
byte day = rtc.getDay();
byte month = rtc.getMonth();
byte year = rtc.getYear();
byte hour = rtc.getHours();
byte minute = rtc.getMinutes();
byte second = rtc.getSeconds();
// Print date and time
Serial.print(day < 10 ? "0" : ""); Serial.print(day);
Serial.print("/");
Serial.print(month < 10 ? "0" : ""); Serial.print(month);
Serial.print("/");
Serial.print(year);
Serial.print(" ");
Serial.print(hour < 10 ? "0" : ""); Serial.print(hour);
Serial.print(":");
Serial.print(minute < 10 ? "0" : ""); Serial.print(minute);
Serial.print(":");
Serial.print(second < 10 ? "0" : ""); Serial.println(second);
delay(1000);
}
Loading
stm32-bluepill
stm32-bluepill