I can't post the entire source code for my project, but the specific issue I am having is that I have configured a 32bit timer to run on TC0+TC1 (DIV16 prescalar, normal mode, no interrupts on match or rollover) using a modified GCLK4: changed the divider from 4 to 3, giving a 16 MHz clock instead of the default (as per the Adafruit library for this board) 12 MHz . This produces a tick every us and all I wish to do for my application is read out the timer value at various points in my code, both on the main loop and inside ISRs. Please don't say "just use micros()" because there are other reasons for not doing so. Regardless, I believe there is still merit in understanding the situation described below and working out how to fix it.
My code for reading the timer looks like this:
Code: Select all
uint32_t ReadTimer() {
// write READSYNC command to the Control B Set register
TC0->COUNT32.CTRLBSET.reg = TC_CTRLBSET_CMD_READSYNC;
// Wait for sync
while (TC0->COUNT32.SYNCBUSY.bit.ENABLE);
// Get the 32bit value from the timer
return TC0->COUNT32.COUNT.reg;
}
I suspect this is due to some ISR happening while my ReadTimer() function is trying to work on the main loop and the read sync is lost - though I'd then expect the read to return 0 rather than the last value used, so I'm far from having a deep understanding of this.
A potential workaround is to keep a local record of the last result returned by the read, and if it hasn't changed, then try the read again. This seems a little ugly and will cause wasteful delays if I do end up calling the function in rapid succession (for whatever reason, intentional or otherwise). I'd rather understand what is occurring and whether there is something more elegant, like mastering the sync system.
Thank you in advance if you are able to offer any assistance.