Teensy 4.0 clock drift correction

Status
Not open for further replies.

snowface

Member
Hello,
I am collecting a data stream from an I2C device on Teensy 4.0, and timestamping this data based on Teensy micros(). We believe that the teensy micros() is drifting by 100 ms per hour. Following is our source code, is there a way to correct for this timestamp without external RTC. I understand Teensy 4.0 has internal RTC, any code sample on how to use it would also be helpful. Thank you

#include <Wire.h> //For I2C/SMBus
#include <stdio.h>

unsigned long counter = 0;

void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(115200); // start serial for output
Serial.flush();


while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

}

void readDataFromSensor(short address, short *data, unsigned long *myTime)
{

*****fetch data*****

*myTime = millis();
}

void loop()
{
short data1; unsigned long myTime1;
byte i2cAddress1 = 0x11;
readDataFromSensor(i2cAddress1, &data1, &myTime1);

Serial.print("{");
Serial.print(i2cAddress1);
Serial.print(",");
Serial.print(myTime1);
Serial.print(",");
Serial.print(data1);
Serial.print(",");
Serial.print(counter);
Serial.println("}");

short data2; unsigned long myTime2;
byte i2cAddress2 = 0x05;
readDataFromSensor(i2cAddress2, &data2, &myTime2);

Serial.print("{");
Serial.print(i2cAddress2);
Serial.print(",");
Serial.print(myTime2);
Serial.print(",");
Serial.print(data2);
Serial.print(",");
Serial.print(counter);
Serial.println("}");

counter += 1;
}
 
You could get more accuracy by multiplying millis() by some floating point adjustment value (close to 1.0).
 
100ms per hour is about 27 ppm for your T4 24mhz crystal -- that's a little high, but each crystal is different. The RTC runs from a 32khz crystal which has its own frequency error. Here are some anecdotal crystal offsets for various Teensy 4s
https://forum.pjrc.com/threads/54711-Teensy-4-0-First-Beta-Test?p=195166&viewfull=1#post195166
You can get submillisecond RTC values from this example
https://forum.pjrc.com/threads/6806...onds-correctly?p=288688&viewfull=1#post288688
precision is 1/32768 (bout 30 microseconds).

As jonr suggests, you could calculate a drift correction and apply it each time you need a time-stamp. Note that frequency/error can change with temperature. A GPS PPS signal is useful in calculating the correction for a given crystal.
 
Status
Not open for further replies.
Back
Top