Postscript:
I did some testing of the code change and (surprisingly) it seems to make no difference in timing.
Here's the relevant code in delayMicroseconds function
// code A
// if (--us == 0) // decrement to offset function overhead
// return;
Here's the code fix
// code B
if ((int)us < 2 ) // cast cures negative number rollover
return;
us--; // decrement to offset function overhead
code A is the original and code B is the fix.
I can detect absolutely no difference in the testing I did except code B fixes the issues.
Here's the test setup (I can see your eyes glazing over - snap out of it!)
/* Test delayMicroseconds() with param of zero
*/
int tdelay;
unsigned long i, hz;
unsigned long start, TotalLoopTime;
int outPin = 11;
void setup(){
pinMode(outPin, OUTPUT);
Serial.begin(9600);
Serial.println("start");
}
void loop() {
start = millis(); // get start time of loop
for (i = 0; i < 1000000; i++){ // a million times through the loop
delayMicroseconds(2);
}
TotalLoopTime = millis() - start; // compute time through inner loop in milliseconds
Serial.print("time = ");
Serial.println(TotalLoopTime, DEC);
}
Here's the results
value of param 0 1 2 4
Code A rolls over 3011 3953 5959 results in milliseconds
Code B 3011 3011 3953 5959
All of the numbers jitter randomly by one or two, presumably because of interrupt firings or serial.print or some other unknown (to me) phenomenon.
Please replicate my results on this if you care, then can we finally fix the code and move on?
A more patient math-head than me might also want to see if the function is as advertised, with about 1 us going into the function overhead.
There is another decrement farther down in the code that could be combined with the decrement to tweak timing. Should anyone care to get into it. I imagine it's only going to be possible to confirm this through some patient work with an oscilloscope or through sorting through the machine code and counting instructions, though. I'm not up for either at this point.
Yours in easy-to-use microcontroller code,
Paul Badger