I was having problems with timing my stepper project, and realized that the delayMicroseconds is all over the place for larger numbers. I think it should either be fixed or have documentation update to indicate the problem. I am attaching the simple test sketch so you can see the values for yourself. I am also attaching a log of the run. The values are pretty consistent from run to run. The pattern repeats and gets as small as returning after waiting for as little as 1% of the requested time. I verified this on both a nanoV3.0 atmega238 and an Arduino Mega.
Here is the test code try it for yourself.
Please let me know if there is something wrong with the test. I realize the times are quite large and could easily be converted to use the delay() function, but it was still a big head scratcher trying to figure out what went wrong when I was seriously slowing down my stepper motor for some testing and it was stepping way faster than expected because of this issue.
In the log you can see it pass through repeated plateaus of around 16K micro seconds and the start over again. The larger values never get close to the correct wait time.
My arduino version is 1.8.1 (I attached a pic of my about box).
#define pulseMicroSecondDelay 60000 // microseconds delay starting value
#define stepDown 100 // decrement this much for each test
// current delay
unsigned long delayMicroSeconds = pulseMicroSecondDelay;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); // setup the interal serial port for debug messages
Serial.println("Setup complete");
}
unsigned long before; // ms before delay
unsigned long after; // ms after dealy
unsigned long diff; // ms difference between before and after
void loop() {
//collect the timings.
before = micros();
delayMicroseconds(delayMicroSeconds);
after = micros();
diff = after - before;
// print some diagnostics, after we have collected our stats
Serial.print("Delay:");
Serial.print(delayMicroSeconds);
Serial.print(", ms before:");
Serial.print(before);
Serial.print(", ms after:");
Serial.print(after);
Serial.print(", ms diff:");
Serial.print(diff);
Serial.print(", percent of expected: ");
Serial.println((diff/(delayMicroSeconds*1.0)) * 100.0, 4);
// decrement the delay, or loop around to the top when we get <= our step value
if (delayMicroSeconds <= stepDown ) {delayMicroSeconds = pulseMicroSecondDelay; } else { delayMicroSeconds -= stepDown; }
}
delayMicrosecondslog.txt (113 KB)
Arduino Version.pdf (117 KB)