We take our epoch time from NTP and set the DS3231.
uint32_t ntpTime = esp32Time.getEpoch();
rtcExt.adjust(DateTime(ntpTime));
All well and good. The Unix times match for ESPtime the ESP32 onboard crystal clock and the DS3231.
But, the time display of the DS3231 reverts to UTC!
So, something is going on here and I've just gone code blind!
OUTPUT:
=== Onboard RTC Epoch Time: 1719579197
=== External RTC Epoch Time: 1719579197
=== Onboard RTC Time: 19:53:17
=== External RTC Time: 12:53:17
=== ESP32Time Time: 19:53:17
#include "RTClib.h"
#include <WiFi.h>
#include <ESP32Time.h>
// Replace with your network credentials
const char* ssid = "XXXXX";
const char* password = "XXXXX";
// NTP servers to request time from
const char* ntpServer1 = "pool.ntp.org";
const char* ntpServer2 = "asia.ntp.org";
const long gmtOffset_sec = 25200;
const int daylightOffset_sec = 0;
RTC_DS3231 rtcExt; //==== External RTC DS3231
ESP32Time esp32Time; //==== ESP32 Time library
ESP32Time rtcOB(0); //==== ESP32 onboard Crystal RTC
#define TIME_24_HOUR true
void setup() {
Serial.begin(115200);
while (!Serial)
// Initialize WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
/*---------set with NTP using struct---------------*/
struct tm timeinfo;
while (!getLocalTime(&timeinfo)) {
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer2);
struct tm timeinfo;
if (getLocalTime(&timeinfo)) {
// Set time to ESP32Time getLocalTime
esp32Time.setTimeStruct(timeinfo);
}
}
// Initialize RTC
if (!rtcExt.begin()) {
Serial.println("Couldn't find RTC");
while (1)
;
}
// Get the epoch time from ESP32Time
uint32_t ntpTime = esp32Time.getEpoch();
//Onboard RTC of the ESP32
rtcOB.setTimeStruct(timeinfo);
// Set DS32321 to ESP32 Epoch Time
rtcExt.adjust(DateTime(ntpTime));
// disconnect WiFi
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
// Function to get and return a formatted string of RTC time
String getRTCTimeString() {
DateTime now = rtcExt.now();
char buffer[10]; // Buffer to hold formatted time string
sprintf(buffer, "%02d:%02d:%02d",
now.hour() + 7, now.minute(), now.second());
return date;
}
void loop() {
// Print the epoch time from ESP32Time
Serial.print("=== Onboard RTC Epoch Time: ");
Serial.println(rtcOB.getEpoch());
// Print the time from onboard RTC
Serial.print("=== Onboard RTC Time: ");
Serial.println(rtcOB.getTime());
// Display RTC time using the function
Serial.print("=== External RTC Time: ");
Serial.println(getRTCTimeString());
// Print the epoch time from RTC
Serial.print("=== RTC Epoch Time: ");
Serial.println(rtcExt.now().unixtime());
Serial.println("===================================="); // Separator line
delay(10000);
}