Microseconds per second

jeremy-daily

New member
I've created a simple sketch that provides a way to get microseconds in a timestamp. I'm interested in any alternatives.
Does the setSyncInterval() function create an interrupt so the microsecond reset counter is always called on time?
Code:
#include <TimeLib.h>

elapsedMicros microsecondsPerSecond;

time_t getTeensy3Time(){
  microsecondsPerSecond = 0; // Reset the microsecond timer
  return Teensy3Clock.get();
}

void setup() {
  // put your setup code here, to run once:
  setSyncProvider(getTeensy3Time);
  setSyncInterval(1); //must be on a 1 second interval to get the microseconds to sync.
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  char timeString[22];
  sprintf(timeString,"%04d-%02d-%02d %02d:%02d:%02d.%06d",year(),month(),day(),hour(),minute(),second(),uint32_t(microsecondsPerSecond));
  Serial.println(timeString);
}
 
Nice idea! I was wondering how to do it...
You could add '% 1000000' such that there is no need to sync every second.
C++:
sprintf(timeString,"%04d-%02d-%02d %02d:%02d:%02d.%06d",year(),month(),day(),hour(),minute(),second(),uint32_t(microsecondsPerSecond)%1000000);

However there is a glitch, when the second counter is incrementing, the microseconds could be still at 999999. (same for just before the seconds are changing)

I believe without taking the time with 'now()' twice(maybe with a small amount of microseconds delay in between them), there is no way to get ride of that glitch... microseconds are not part of the RTC anyways, so the sync basically adds a jitter of 1 second when the sync is executed at random times.

C++:
time_t t = now();
uint32_t t_us = uint32_t(microsecondsPerSecond) % 1000000;
delayMicroseconds(5);
time_t t2 = now();
if (t != t2) // we are flipping the second counter...
{   
  uint32_t t_us = uint32_t(microsecondsPerSecond) % 1000000;
  t = t2;
}
tmElements_t tm;
breakTime(t, tm);
sprintf(timeString,"%04d-%02d-%02d %02d:%02d:%02d.%06d", tm.Year+1970, tm.Month, tm.Day, tm.Hour, tm.Minute, tm.Second, t_us);

However, yes, this comes with a penalty!
 
Back
Top