Wednesday, February 4, 2009

Delays

Delays are used in code to pause for a specific amount of time, usually to allow humans to read output. But they are also important when interfacing peripherals. For example, when interfacing a microcontroller to an HD44780 LCD, enough time must be given for the LCD module to complete its operation. For this purpose, delays are used to waste time. There are numerous ways to implement delay functions. For example, one may chose to use the built in delay functions in C18, impliment their own using inline assembler for greater timing precision or use the timer module. The easiest way to use delays are to use the built in delay functions in C18. All you have to do is #include to use the delay functions. However, the delay functions are not a function of time - that is, they do not accept units of time as arguments. Instead, they delay for multiples of instructions. Therefore, to create times delays (1 second, 500 milliseconds, 45 microsecodns), it is important to calculate the number of instructions based on your clock speed. In the previous post, we configured the internal clock source to its highest setting for the PIC18F2620 - 8 MHz. PIC18 chips take 4 clock cycles for each instruction. So the frequency of executed instructions is 8 MHz / 4 = 2 MHz. The instructions execute at a frequency of 2 MHz. Taking the inverse of this value, we get the period (the time each instruction takes to execute). The value is 1/2000000 s per instruction. This is equal to 0.5 microseconds per instruction. We now know that each instruction takes 0.5 microseconds (a millionth of a second). We can now easily create our delay functions. By including delays.h, you now have access to the following built-in delay functions: Nop(); //Delay one instruction cycle Delay10TCYx(unsigned char N); // Delay in multiples of 10 instruction cycles. Delay100TCYx(unsigned char N); // Delay in multiples of 100 instruction cycles. Delay1KTCYx(unsigned char N); // Delay in multiples of 1000 instruction cycles. Delay10KTCYx(unsigned char N); // Delay in multiples of 10000 instruction cycles. The above functions delay in multiples of instruction cycles. If you want to create a function to delay 1 second (1 million microseconds), you need to delay 2 million instruction cycles (since each instruction cycle takes half a microsecond at our specified clock frequency). Here's a function that delays one second: void delay1s() { Delay10KTCYx(200); //Delay 2 million instruction cycles } As you can see, it is trivial to create your own custom delay functions using the delays.h funcions provided.

No comments:

Post a Comment