setSyncProvider of TimeLib.h with DS3231

I'm using the TimeLib.h library to keep track of time. This is working fine. When I try to tell it to get the time from the DS3231 using the setSyncProvider , it outputs absolutely nothing.

It is pulling the time from the setSyncProvider - I know this because if I set the value of timeUL in time_provider() to a value e.g. 2000000, it prints a time to the serial monitor every second, and starts again from the same time every 5 seconds.

I also know that rtc.getUnixTime(rtc.getTime()); does return the epoch time as it works when I try calling it from setup().

Can anyone tell me what I may be doing wrong?

#include <TimeLib.h>
#include <DS3231.h>                           // For real time clock

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);

void setup() {
  
  setSyncProvider(time_provider);
  setSyncInterval(5);
  Serial.begin(9600);
  Serial.println();

  // Initialize the rtc object
  rtc.begin();

  // Test
  Serial.println(rtc.getUnixTime(rtc.getTime()));
  Serial.println();
}

void loop() {

   digitalClockDisplay();
   delay(1000);
}

void digitalClockDisplay(){

   // digital clock display of the time
   Serial.print(hour());
   printDigits(minute());
   printDigits(second());
   Serial.print(" ");
   Serial.print(day());
   Serial.print(" ");
   Serial.print(month());
   Serial.print(" ");
   Serial.print(year());
   Serial.println();
}

void printDigits(int digits) {
   // utility function for digital clock display: prints preceding colon and leading 0
   Serial.print(":");
   if(digits < 10)
      Serial.print('0');
      Serial.print(digits);
}


time_t time_provider() {

  time_t timeUL;
  timeUL = 200000000;  //rtc.getUnixTime(rtc.getTime());  
  return timeUL;

}

How are you coding the setSyncProvider() function when using the RTC?

Which library are you using for the RTC? There are multiple libraries with the DS3231.h header file.

Not sure what you mean by how am I coding it? I've set the provider as the function time_provider() in the code in the post. In time_provider(), I want to use rtc.getUnixTime(rtc.getTime()) but it seems to break, the code doesn't output anything as soon as I use the rtc functions.

Re the DS3231, I'm using the one by Henning Karlsen

You need to call rtc.begin() before you call setSyncProvider().
When you call setSyncProvider(), the library calls the sync function to set the time, and this does not work if you have not yet initialized the RTC.

That was it, thanks very much!

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