delay function working using for loop

Discussion in 'Embedded Systems and Microcontrollers' started by ect_09, Sep 28, 2014.

  1. ect_09

    Thread Starter Member

    May 6, 2012
    i want to know the basic understanding of delay function, how its working.
    Code (Text):
    1. void delay_sec(unsigned char seconds)    // This function provides delay in terms of seconds
    2. {
    3.     unsigned char i,j;
    5.     for(i=0;i<seconds;i++)
    6.         for(j=0;j<100;j++)
    7.             __delay_ms(10);
    8. }
    please explain this.
  2. djsfantasi

    AAC Fanatic!

    Apr 11, 2010
    For each loop, the microcontroller needs a discrete amount of time to increment the variable and test to see if it has hit a limit. This is a base delay. By repeating these operations in a loop, longer delays can be constructed. This is called a "blocking delay" because the microcontroller is blocked from doing anything else because it is busy counting.

    In your code example, an intrinsic delay function is used to delay for 10ms. It is in a loop of 100, which results in a one second delay. 10ms x 100 = 1000ms or 1 second. An outer loop counts the number of seconds desired for the delay. I can tell because of the clever use of a variable name - seconds. It's good practice to use meaningful variable names. And function names - delay_sec
  3. shteii01

    AAC Fanatic!

    Feb 19, 2010
  4. ScottWang


    Aug 23, 2012
    unsigned char i,j; ← To setup the type of variables.

    for(i=0;i<seconds;i++) ← The i variables plus +1 each times from 0 to seconds-1, it will exit the loop when i=seconds.
    for(j=0;j<100;j++) ← The j variables plus +1 each times from 0 to 100-1, it will exit the loop when i=100.
    __delay_ms(10); ← Call the 1 ms function 10 times, so it will delay 10 ms.

    The other details to see the explanation from djsfantasi on #2.
  5. ect_09

    Thread Starter Member

    May 6, 2012
    if you write delay function then what would be??
  6. djsfantasi

    AAC Fanatic!

    Apr 11, 2010
    It is not clear what you are asking? If you are asking what the "_delay_ms_" is or how you would write it, you don't have to. It is an intrinsic function, that is built in. Just like the "for" statement.
  7. adam555

    Active Member

    Aug 17, 2013
    The simplest option is to just use the __delay_ms() function alone; you just enter the milliseconds you want it to delay and that's it.

    However, there is a limit on the delay you can use; which I found this weeks also depends on the particular PIC and the value of _XTAL_FREQ (which you need to define before using __delay_ms()) ; and that's when you need the loop.