Wednesday, September 29, 2010

Delay Loops

There is one slight drawback to our flashing LED program.  Each instruction takes one clock cycle to complete.  If we are using a 4MHz crystal, then each instruction will take 1/4MHz, or 1uS to complete.  As we are using only 5 instructions, the LED will turn on then off in 5uS.  This is far too fast for us to see, and it will appear that the LED is permanently on.  What we need to do is cause a delay between turning the LED on and turning the LED off.
The principle of the delay is that we count down from a previously set number, and when it reaches zero, we stop counting.  The zero value indicates the end of the delay, and we continue on our way through the program.

first we define our constant:  
COUNT          equ       08hNext we need to decrease this COUNT by 1 until it reaches zero.  It just so happens that there is a single instruction that will do this for us, with the aid of a ‘goto’ and a label.  The instruction we will use is:
DECFSZ        COUNT,1
 This instruction says ‘Decrement the register (in this case COUNT) by the number that follows the comma.  If we reach zero, jump two places forward.’  A lot of words, for a single instruction. Let us see it in action first, before we put it into our program.
COUNT          equ 08h
LABEL           decfsz   COUNT,1
                        goto LABEL
                        Carry on here.
 What we have done is first set up our constant COUNT to 255.  The next line puts a label, called LABEL next to our decfsz instruction.  The decfsz COUNT,1 decreases the value of COUNT by 1, and stores the result back into COUNT.  It also checks to see if COUNT has a value of zero.  If it doesn’t, it then causes the program to move to the next line.  Here we have a ‘goto’ statement which sends us back to our decfsz instruction.  If the value of COUNT does equal zero, then the decfsz instruction causes our program to jump two places forward, and goes to where I have said ‘Carry on here’.  So, as you can see, we have caused the program to stay in one place for a predetermined time before carrying on.  This is called a delay loop.  If we need a larger delay, we can follow one loop by another.  The more loops, the longer the delay.  We are going to need at least two, if we want to see the LED flash..

No comments:

Post a Comment