cancel
Showing results for 
Search instead for 
Did you mean: 

Generating a delay using "wasted" instructions

VVarg.1
Associate II

Hi All,

Using an STM32F429 and reading online documentation I have come frequently to this code used for generating delays in Ms if the SYSCLK is 16Mhz

void delayMs(uint32_t n)
{
    int i;
    for (; n > 0; n--)
        for (i = 0; i < 3195; i++) ;
}

I cant understand why the 3195 value is used?

In my understanding for achieving 1Ms of delay we will need

FOSC=16MHz

TOSC=1/16Mhz = 62.5nS

For 1Ms, then I can calculate how many cycles need to be "burned" by the following equation:

My_1_Ms_counter = 1mS / TOSC = 0.001 / 62.5nS = 16000

In summary I will need 16000 dummy instructions to be performed in order to obtain 1Ms of code execution (thus delay).

I come back to my questions of why does the 3195 is used?

Thanks

14 REPLIES 14

Hi @TDK​ , yes I also agree. Thank you both

Hi @Terry Greeniaus​ , what a superb explanation thanks. It took me three reads of your post to fully understand what's going on. Great to see how experts can provide these in-depth insights.

I didn't, I just determined it was an entire waste of energy and time to get inside the code author(s) head, as to why/how it "worked for them"

Like analyzing Eighteen Century Romantic Poetry, or making 999 non-working light bulbs to get full coverage of the problem space..

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

Indeed a great comparison. Check @Terry Greeniaus​  post where he elaborates and educates us about it, hope you find it interesting as well. I found it interesting that you claim it's a waste of time while actively replying to this post.

Uwe Bonnes
Principal III

Declaring "i" as volatile will help somehow