Off by one in delay() on Teensy 3.0?

banahogg

New member
I had some code with delays that wasn't working quite right, so I modified the blink example to do a shorter delay:

Code:
void loop() {
  digitalWrite(ledPin, HIGH);   // set the LED on
  delay(2);                  // wait for a second
  digitalWrite(ledPin, LOW);    // set the LED off
  delay(2);                  // wait for a second
}

When I hooked the output pin up to my multimeter, it said the pulse width was 3.002 ms, not ~2ms. Making the following change fixed my test:

Code:
void delay(uint32_t ms)
{
	uint32_t start = micros();

	while (1) {
		if ((micros() - start) >= 1000) {
+++			ms--;
			if (ms == 0) break;
---			ms--;
			start += 1000;

That obviously breaks delay(0), but that's probably best handled by an early-out at the top anyway (the current code waits 1ms for delay(0)).
 
Back
Top