Skip to content

micros() & delayMicroseconds() not good enough #282

@rosimildo

Description

@rosimildo

Calling micros() twice is in a row, takes nearly 50uS.

Something line:

uint32_t t0 = micros();
uint32_t t1 = micros();
uint32_t delta_t = t1 - t0;
printf( "Delta = %u\n", delta_t ); // this prints around 51 on my system.

Looking at the implementation of micros() and delayMicroseconds(), it is clear they have too much overhead.

The code is trying to deal with "overflow" and entering critical sections, which is totally unneeded.

When you are dealing with "unsigned numbers", there is no such a thing like "overflow". It is a thing of signed numbers. Unsigned numbers rolls over, and that is it.

So you could implement these functions as:

inline uint32_t IRAM_ATTR micros()
{
uint32_t ccount;
asm volatile ( "rsr %0, ccount" : "=a" (ccount) );
return ccount;
}

void IRAM_ATTR delayMicroseconds(uint32_t us)
{
if(us){
uint32_t m = micros();
while( (micros() - m ) < us ){
NOP();
}
}
}

Even better, if "micros()" as inline in a header.

Rosimildo

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions