I'm using the micros() call in Energia to get the microsecond timer and using it to calculate speeds for a quadrature decoder on a Tiva C Launchpad TM4C123GXL.
But I am running into problem with the microsecond timer (micros() call in Energia) going briefly backwards. I know about wraparound since micros() returns an unsinged long I expect that it would wrap around after a while, but this is going backwards when the counter is nowhere near the point when it should wrap.
I wrote a program to collect time values returned by micors() in the loop and print out the saved values when I detect an error. Here is an example of what I get (older time values are further down, newer value are on top).
5025005
5024001 <<< went backward here, should have been 5025001
5024996
5024992
5024989
5024985
Notice that that the count goes from 5024996 to 5024001, and then 5025005 as if the carry to the 1000's digit gets delayed.
This happens multiple times, always on the same 1000's digit. And I have tried this on two different parts with the same result.
Here is another example:
5401005
5400001 <<< went backward here
5400996
5400992
5400989
5400985
Can anyone let me know if I'm doing something wrong or if this is a bug. I know I can work around it but it seems like a hack to do so.
When you see the word "Last" appear in the serial output, then the next few counts are the ones to look at.
Here is the code to reproduce:
unsigned long prevus[1000]; unsigned long lastus = 0; int idx = 0; int printnext = 0; void setup() { // put your setup code here, to run once: Serial.begin(57600); } void printprev() { Serial.println("Last"); int pidx = idx - 1; for (int count = 0; count < 100; count++) { if (pidx < 0) { pidx = 999; } Serial.println(prevus[pidx]); pidx--; } } void loop() { // put your main code here, to run repeatedly: unsigned long curus; curus = micros(); prevus[idx] = curus; idx++; if (idx > 999) { idx = 0; } if (printnext == 1) { printprev(); printnext = 0; } if (curus < lastus) { printnext = 1; } lastus = curus; }