The Arduino delay routines are not very accurate and are totally inaccurate if the MPU clock rate is not 16Mhz or 8Mhz.
Why is that, Bill? Doesn't the internal timer fire accurately? That would be the only reason for it to be wrong, surely? Just curious.
You are correct in that not using 16Mz or 8Mhz clock are the primary causes for inaccuracy.
I was basing the "inaccuracy" primarily on DrWoo's original sample code that used floating point
and called delayMicroseconds().
If there is a need for delays that are very small (like less than a few microseconds) or need to be a fractional
microsecond value, the existing routines would not be very accurate.
If wasn't clear if the additional accuracy for fractional microseconds was desired.
In general, it is easy to get a delay that is "at least as long as". But trying to get a delay that is "exactly"
a given value no matter how it is implemented is very difficult especially as the needed precision increases.
The Arduino routines like delay(), millis(), and micros(), are actually pretty good at being able to time
durations as long as the durations are not too short or the precision you need is not extremely high.
What is it you want/need when you say:
Maybe I'm nitpicking, but I need accuracy
Accuracy and precision are not the same thing.
How much of each are you needing?
... see this project over on AVR freaks: (you will need to create an account to access this)
Why do you need to create an account just to view information? Is it a secret? Every time I visit a web site (eg. by Google) that requires me to "create an account" just to find a solution to my problem, I close that window and move onto the next search result.
Yep, I'm with you on that one. Normally, I do the same. In fact I didn't realize that you needed
an account to see the AVR freaks projects until I did this post and tried out the link when I wasn't
The only thing to keep in mind is that if interrupts are enabled and ISRs are running (and they are on Arduino), that they are robbing away cycles from the delay loop so that the delays can potentially be longer than what was asked for or can drift in size depending on the interrupt load.
That's true with "count cycles" delays. But the timer delays should be pretty accurate because the hardware timer is doing the timing, and provided the overflow interrupt is serviced in time, other interrupts shouldn't affect the end result.
On Arduino, while the delay(), millis(), and micros() functions use the hardware timer, the delayMicroseconds() function
uses a "count cycles" type spin loop. It does not use a hardware timer.
So it can suffer from "drift" depending on the interrupt load - same is true for the delay routines
from the delay project over on AVRfreaks that I referenced earlier.
perhaps there is just lag executing digitalwrite so many times.
digitalWrite() does take about 4us on a 16Mhz AVR.