2.8 Using Delay function
A time delay is something that is very important when working with embedded applications, because there are times you want a delay before something is begun.
Time delays can also be used for breaks between processes. For example, a time delay in between an LED can make the LED blink on and off, on and off, repeatedly. So time delays can be very useful and important for embedded applications.
A __delay_ms() is not a real function, it is a macro which will expand into in-line assembly instructions or a nested loop of instructions which will consume the specified number of time. So the delay argument must be a constant and can't be changed during runtime. This function is known as the compilerβs in-built delay function.
If you want a real function with a parameter, you had to write it on your own as shown in Figure 2.14.
void delay_ms (unsigned int x) { for(; x>0; x--) __delay_ms(1); //delay 1ms } Figure 2.14: User defined delay function
If an accurate delay is required, or if there are other tasks that can be performed during the delay, then using a timer to generate an interrupt is the best way to proceed. The timer module of PIC will be discussed in the next chapter.
23