How can I test if Spark.syncTime() has finished after startup?

I just found out the hard way that Spark.syncTime() does not happen before setup() is called, but somewhat after or during the first seconds of the [Spark] app running. Before that, Time.minute() etc are set to zero at startup and will count up from there.

I need to be sure that the core has already acquired the time from the network before doing anything else in setup. How can I do this? Thank you so very much.

My current fix is to delay(10000), but that feels like a bad hack.

UPDATE:

Thank you for the useful hints! I would like to add another idea: wait until the year is not 1970 anymore – this is the case before the clock is synchronized with the web.


while(Time.year() == 1970) {  delay(100); }

I found a smallish delay in the loop was necessary for the time fetching process to have some air to breathe.

What if you do something like:

function setup() {
  while (! Time.second()) { /* wait for iiiiiit... */ }
  // at this point, time is running. so we can do the rest of our setup
}
1 Like

Hi @akrusen,

I have a solution but it requires constraining your core to not travel back in time, since then the assumption breaks down :slight_smile:

I think you could check the unix time, and wait for it to be significantly different from the millis counter, for example:

uint32_t last_counter = 0;
bool published = 0;

void setup() {
    
    last_counter = RTC_GetCounter();
    
    Serial.begin(115200);
    Serial.println("MS: " + String(millis()) + " " + String(RTC_GetCounter()));
}

void loop() {
    uint32_t counter = RTC_GetCounter();
    if (!published && (counter > millis())) {
        Spark.publish("Greater", String(last_counter) + " " + String(counter));
        published = 1;
    }
    
    
    Serial.println("MS: " + String(millis()) + " " + String(counter));
}

If you de-power your core entirely, you’ll notice the value will be very very low, and when it’s been set, it’ll be closer to something like 1405536989, which is closer to now. So you could simply check to see if the RTC value is greater than say, Jan 1st, 2014. :slight_smile:

Thanks,
David

2 Likes