Syncing of RTC with NTP / Unix time

I am developing an application to start a motor two times a day for filling pellets to my pellet bunker.
The internet is sometimes flaky and might be off for a few days.
Due to remote location there are regular power outings.

That is the reason that I have a Real Time Clock as central time keeper.

Hence the procedure is:

  • Obtain time from NTP server once in 24 hours.
  • Synchronize the RTC (DS3231) with NTP time when internet works.
  • Synchronize the ESP8266 with the RTC

I have no issues except one:
Despite scouring the internet for hours I have not found a way to update the RTC with Unix time.
I use RTClib.h and the obvious NTP code.
The NTP code gives me a time_t object as Unix time (starting seconds from 1970) say
time_t unixTime
One way seems to be to breakdown 'time_t unixTime' to year - month - etc and to synchronize the RTC with the following format asin RTClib:
rtc.adjust(DateTime(YYYY,mm,dd,hh,mm,ss)
However in the technical docs of RTClib (RTClib: DateTime Class Reference) there is a DateTime constructor:
DateTime::DateTime (uint32_t t = SECONDS_FROM_1970_TO_2000)
(btw the notation is above my level of knowledge)
Would this mean that I could use:
rtc.adjust(DateTime(unixTime))

In a test sketch it seems to work however I am not sure because of other use of EEPROM in the sketch.
I am not copying the complete code now it is quite long and mainly boilerplate hence not adding something to the question I think.

Hope someone can help me. Much appreciated.

I have an example for ESP8266 NTP and RTC, may be it is of any help:

NTP DST and a RTC for the ESP8266 (rothschopf.net)

@noiasca

rtc.adjust(DateTime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec));

With the code you use a struct and update the RTC with yyyy,mm,dd etc
I am looking if the direct use of unix time with DateTime can be done and if it has strange consequences for storage of data in EEPROM or something similar.

so just do it,

time_t now; // this are the seconds since Epoch (1970) - seconds GMT
time(&now); // read the current time and store to now

... now is current time now. Use that to adjust your RTC.

I have done it now as follows:

time_t F_getNTP() { ...................... }
This function provides NTP time as Unix time (from 1970)

Update the RTC with:

rtc.update(DateTime(F_getNTP());

The RTC is updated correctly. Still don't know of by-effects on EEPROM or so.

Would there be any?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.