Accuracy, Consistency of micros() function

Status
Not open for further replies.

Cyclist

Member
I use the micros() function to create a one-second ticker that must remain very consistent. The simplified code looks like this:

oneSec = 1000000;

void loop()
{
do { } while (micros() - secTime <= oneSec); // Kill time until one second is complete

digitalWrite(ledPin, HIGH); // Blink LED.
delay(5);
digitalWrite(ledPin, LOW);

// Do lots of stuff that takes less than one second

secTime = secTime + oneSec;

} // End of Main Loop

This one-second ticker code runs very accurately and consistently, verified by comparing the LED pin rising edge to an accurate, independent one-second pulse on an o-scope.

BUT if I include the "lots of other stuff" in my code (hundreds of lines), the one-second ticker produced by the micros() function slows down by nearly one percent and is inconsistent.
My question: Are there known functions or operations that would affect this timing code? Are there specific operations or functions that I should avoid to improve accuracy and consistency?

Thanks!
 
not shown enough to have a running sketch. Including var type and init of secTime.

Generally no - unless interrupts are off of skipped the clock isn't affected by running code.

Look into elapsedMicros - a handy PJRC creation to track time in a similar fashion
 
If the "lots of other stuff" code (which we can't see) disables interrupts for more than 1 ms, then the systick (Teensy LC & 3.x) or timer0 (Teensy 2.0) interrupt will not be able to keep proper time. Most code doesn't do this, but there are some notable exceptions like Adafruit_Neopixel.

Using IntervalTimer may help, but only if that stuff all completes and has interrupts enabled again when the interval completes.
 
I see now that I disabled interrupts for a brief period, code that was lifted from another program. I should have known better as I recall seeing this point in other tutorials. I was able to eliminate this code and timing is now much more accurate and consistent.
Thanks for the tip on the TimerOne library, brtraylor. I will check it out for future use.
Thank you all for very prompt and helpful responses!
 
Status
Not open for further replies.
Back
Top