Skip to content

Delay yield #4320

Closed
Closed
@vbextreme

Description

@vbextreme

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;
        }
    }
}

Metadata

Metadata

Assignees

Labels

Architecture: AVRApplies only to the AVR microcontrollers (Uno, etc.)Component: CoreRelated to the code for the standard Arduino APIType: Bugfeature requestA request to make an enhancement (not a bug fix)

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions