From 2d52fcd851447197691c9adc3d75b77c26444fa7 Mon Sep 17 00:00:00 2001 From: Vitali Date: Fri, 17 Jul 2026 19:55:47 +0700 Subject: [PATCH] feat: DS3231 RTC read/set with lost-power detection Co-Authored-By: Claude Opus 4.8 --- WeatherPredictor/WeatherPredictor.ino | 13 ++++++++++--- WeatherPredictor/rtc_time.cpp | 20 ++++++++++++++++++++ WeatherPredictor/rtc_time.h | 13 +++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 WeatherPredictor/rtc_time.cpp create mode 100644 WeatherPredictor/rtc_time.h diff --git a/WeatherPredictor/WeatherPredictor.ino b/WeatherPredictor/WeatherPredictor.ino index 3ab0942..44692bd 100644 --- a/WeatherPredictor/WeatherPredictor.ino +++ b/WeatherPredictor/WeatherPredictor.ino @@ -3,6 +3,7 @@ #include "config.h" #include "display_ui.h" #include "sensors.h" +#include "rtc_time.h" static void i2cScan() { Serial.println(F("I2C scan:")); @@ -28,12 +29,18 @@ void setup() { displaySplash("Weather", "Predictor v0.1"); if (!sensorsBegin()) Serial.println(F("BMP180 not found!")); + if (!rtcBegin()) Serial.println(F("DS3231 not found!")); + if (rtcLostPower()) { + Serial.println(F("RTC lost power -> setting to build time")); + rtcSet(RtcTime{2026, 7, 17, 12, 0, 0}); // temporary; NTP will correct later + } } void loop() { + RtcTime t = rtcNow(); float abs_ = readAbsPressureHpa(); - float msl = toSeaLevelHpa(abs_, DEFAULT_ALTITUDE_M); - Serial.printf("abs=%.1f hPa msl=%.1f hPa t=%.1f C\n", - abs_, msl, readTemperatureC()); + Serial.printf("%04u-%02u-%02u %02u:%02u:%02u abs=%.1f msl=%.1f t=%.1f\n", + t.year, t.month, t.day, t.hour, t.minute, t.second, + abs_, toSeaLevelHpa(abs_, DEFAULT_ALTITUDE_M), readTemperatureC()); delay(2000); } diff --git a/WeatherPredictor/rtc_time.cpp b/WeatherPredictor/rtc_time.cpp new file mode 100644 index 0000000..fa2a1d3 --- /dev/null +++ b/WeatherPredictor/rtc_time.cpp @@ -0,0 +1,20 @@ +#include +#include "rtc_time.h" + +static RTC_DS3231 rtc; + +bool rtcBegin() { return rtc.begin(); } +bool rtcLostPower() { return rtc.lostPower(); } + +RtcTime rtcNow() { + DateTime n = rtc.now(); + return RtcTime{ n.year(), n.month(), n.day(), n.hour(), n.minute(), n.second() }; +} + +void rtcSet(const RtcTime& t) { + rtc.adjust(DateTime(t.year, t.month, t.day, t.hour, t.minute, t.second)); +} + +uint32_t rtcEpoch() { + return rtc.now().unixtime(); +} diff --git a/WeatherPredictor/rtc_time.h b/WeatherPredictor/rtc_time.h new file mode 100644 index 0000000..d654016 --- /dev/null +++ b/WeatherPredictor/rtc_time.h @@ -0,0 +1,13 @@ +#pragma once +#include + +struct RtcTime { + uint16_t year; + uint8_t month, day, hour, minute, second; +}; + +bool rtcBegin(); +bool rtcLostPower(); +RtcTime rtcNow(); +void rtcSet(const RtcTime& t); +uint32_t rtcEpoch();