I want to implement a very simple delay function with more or less this look:

void delay(float seconds){
 int i;
 for(i=0; i<seconds*5000000; i++);

It is just based on the clock cycles (doing some tests I have assumed that 5000000 cycles are 1 second) but it doesn't work at all. Instead, it waits forever, but using

void delay(float cycles){
 int i;
 for(i=0; i<cycles; i++);

just work fine if for example I want for the program to wait 2 seconds making cycles=10000000, does anyone know why?

  • \$\begingroup\$ All STM32s have a SysTick interrupt which can be set to fire every nth CPU clock cycle - traditionaly it is set to 1ms and increments a counter in the ISR which is then checked to implement the delay. \$\endgroup\$ – Jan Dorniak Apr 10 '18 at 16:53

In your first example, the multiplication of the seconds float by 5000000 is evaluated at each iteration, to check the end condition. Which is very very slow (and make it look like it lasts forever).

change to:

int i, max = (int)(seconds*5000000);
for(i=0; i<max; i++);

This will evaluate seconds*5000000 only once, before the loop.

Also, be careful that if optimizations are enabled, depending on the compiler, any of the above sample codes may be optimized out completely (as there are no side effects the compiler will see), and you'll end up with no delay at all. To prevent the compiler doing this, you can declare i as volatile.

  • 3
    \$\begingroup\$ If 'i' is declared as volatile the compiler will not optimize it out. \$\endgroup\$ – filo Apr 10 '18 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.