Let us look at a subroutine:
To start the subroutine from anywhere in our program, we simply type the instruction CALL followed by the subroutine name.
Let us look at this in slightly more detail. When we reach the part of our program that says CALL xxx, where xxx is the name of our subroutine, the program jumps to wherever the subroutine xxx resides. The instructions inside the subroutine are carried out. When the instruction RETURN is reached, the program jumps back to our main program to the instruction immediately following our CALL xxx instruction.
You can call the same subroutine as many times as you want, which is why using subroutines reduces the overall length of our program. However, there are two things you should be aware of. First, as in our main program, any constants must be declared before they are used. These can be either declared within the subroutine itself, or right at the start of the main program. We would recommend that you declare everything at the start of your main program, as then you know that everything is in the same place. Secondly, you must ensure that the main program skips over the subroutine. What We mean by this is if you put the subroutine right at the end of your main program, unless you use a ‘Goto’ statement to jump away from where the subroutine is, the program will carry on and execute the subroutine whether you want it to or not. The PIC does not differentiate between a subroutine and the main program.
Let us look at our flashing led program, but this time we will use a subroutine for the delay loop. Hopefully, you will see how much simpler the program looks, and also you will see how the subroutine works for real.
;*****Set up the Constants****
Start movlw 02h ;Turn the LED on by first putting it
;****Add a delay
call Delay
;****Delay finished, now turn the LED off****
;****Add another delay****
call Delay
;****Now go back to the start of the program
goto Start ;go back to Start and turn LED on again
;****Here is our Subroutine
DelayLoop1 decfsz COUNT1,1 ;This second loop keeps the LED
;****End of the program****
end ;Needed by some compilers, and also
For those of you who are interested, our original program was 120 bytes long. By using the subroutine, we have reduced our program size down to 103 bytes. This may not seem to be that great, but seeing that we only have 1024 bytes in total inside the PIC, every little bit helps.
In the next tutorial, we will look at reading from the ports.











