Microseconds per second


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?
#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:
  setSyncInterval(1); //must be on a 1 second interval to get the microseconds to sync.

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));
Nice idea! I was wondering how to do it...
You could add '% 1000000' such that there is no need to sync every second.
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.

time_t t = now();
uint32_t t_us = uint32_t(microsecondsPerSecond) % 1000000;
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!