Closed
Description
While writing a port official scheduler I realized that the delay() function has a bug.
this is official delay() function
void delay(unsigned long ms)
{
uint16_t start = (uint16_t)micros();
while (ms > 0) {
yield();
if (((uint16_t)micros() - start) >= 1000) {
ms--;
start += 1000;
}
}
}
This code assumes that the task called from delay lasts less than a millisecond , otherwise you can get up to an infinite loop.
simple solution:
void myDelay(unsigned long ms)
{
if ( 0 == ms ) return;
uint32_t sm = micros();
uint32_t sM = millis();
while( millis() - sM < ms - 1 ) yield();
ms *= 1000;
while( micros() - sm < ms - 1 );
}
It works with the same precision but should be free of bugs.
or
void myDelay(unsigned long ms)
{
uint32_t start = micros();
while (ms > 0) {
yield();
while ( ms > 0 && (micros() - start) >= 1000) {
ms--;
start += 1000;
}
}
}