delay function working using for loop

Thread Starter

ect_09

Joined May 6, 2012
180
hello,
i want to know the basic understanding of delay function, how its working.
Code:
void delay_sec(unsigned char seconds)    // This function provides delay in terms of seconds
{
    unsigned char i,j;

    for(i=0;i<seconds;i++)
        for(j=0;j<100;j++)
            __delay_ms(10);
}
please explain this.
 

djsfantasi

Joined Apr 11, 2010
9,156
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
 

ScottWang

Joined Aug 23, 2012
7,397
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.
 

Thread Starter

ect_09

Joined May 6, 2012
180
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.
if you write delay function then what would be??
:)
 

djsfantasi

Joined Apr 11, 2010
9,156
if you write delay function then what would be??
:)
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.
 

adam555

Joined Aug 17, 2013
858
if you write delay function then what would be??
:)
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 for...to loop.
 
Top