I am looking over some code to review and have come across a busy wait as such:
int loop = us*32;
int x;
for(x = 0;x<loop;x++)
{
/*do nothing*/
}
I seem to recall reading that these empty loops can be optimized away. Is this what would happen here or can this work?
The answer is yes, the compiler can optimize out the loop.
Use the volatile
qualifier to avoid the optimization:
int loop = us * 32;
volatile int x;
for (x = 0; x < loop; x++)
{
/*do nothing*/
}
If you are programming in the embedded world read the documentation of your compiler as they usually provide delay functions that wait for a certain number of cycles or microseconds passed in parameter.
For example, avr-gcc
has the following function in util/delay.h
:
void _delay_us(double __us);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With