For a CAN logger project, I am trying to get a reliable timestamp from the RTC with millisecond precision. I have found several topics on this and worked out some code from that, but I get erratic behaviour in the resulting log files. Sometimes, seconds jump back and forth and the log is seemingly not chronological (even though the data says otherwise)
I have a function "rtc_get_ms" that is supposed to give me the actual second and millisecond, in conjunction with Teensyduino's minute(), hour() etc functions.
When writing a CAN message to the buffer, I store the time as such:
The millisecond rtc function is as follows:
What could be the cause of this 'jumping' of seconds? Is it the combination of teensyduino second() and rtc_get_ms()? Is there a proper way to read out the seconds and milliseconds "synchronously"?
Thanks for any advice,
I have a function "rtc_get_ms" that is supposed to give me the actual second and millisecond, in conjunction with Teensyduino's minute(), hour() etc functions.
When writing a CAN message to the buffer, I store the time as such:
Code:
//Store message and time
uint32_t sec, ms;
rtc_get_ms(&sec, &ms);
lbuf[lbuf_head].second = second();
lbuf[lbuf_head].minute = minute();
lbuf[lbuf_head].hour = hour();
lbuf[lbuf_head].day = day();
lbuf[lbuf_head].month = month();
lbuf[lbuf_head].year = year();
lbuf[lbuf_head].millisecond = (unsigned int) ms;
memcpy((void*) &lbuf[lbuf_head].msg, msg, sizeof(CAN_message_t));
lbuf_head++;
if (lbuf_head >= CANBUFSIZE){
lbuf_head = 0;
}
The millisecond rtc function is as follows:
Code:
void rtc_get_ms(uint32_t * seconds, uint32_t * milliseconds){
uint32_t hi1 = SNVS_HPRTCMR;
uint32_t lo1 = SNVS_HPRTCLR;
while (1) {
uint32_t hi2 = SNVS_HPRTCMR;
uint32_t lo2 = SNVS_HPRTCLR;
if (lo1 == lo2 && hi1 == hi2) {
*seconds = (hi2 << 17) | (lo2 >> 15);
*milliseconds = (lo2 & 0b00000000000000000111111111111111);
*milliseconds = ((*milliseconds*1000)/32768);
return;
}
hi1 = hi2;
lo1 = lo2;
}
}
What could be the cause of this 'jumping' of seconds? Is it the combination of teensyduino second() and rtc_get_ms()? Is there a proper way to read out the seconds and milliseconds "synchronously"?
Thanks for any advice,