EXAMPLE 3
Using nested loop
The connection scheme is again the same. To make this a bit more
interesting, a different combination of port B bits change each other.
And, that’s not all of course. As seen from the previous two examples,
the microcontroller is very fast and often, it needs to be slowed down.
The use of the built-in oscillator LF, as in example 2, is the last
measure that should be applied. The problem is more often solved by
using nested loops in a program. In this example, the variable
"counter1" is decremented 255 times by 1 in the shorter loop1. Prior to
leaving this loop, the program will countdown 255 times from 255 to 0.
It means that between only two LED diode’s blink on the port, there are
255x255 pulses coming from the quartz oscillator. Precisely speaking,
the number of pulses amounts to approximately 196 000 since it also
takes some time to execute jump instructions and decrement instructions.
Yes, it’s true, the microcontroller mostly waits and does nothing...
Source Code
;******************* Header ***********************************************
;************* DEFINING VARIABLES *****************************************
cblock 0x20 ; Block of variables starts at address 20h
counter1 ; Variable "counter1" at address 20h
counter2 ; Variable "counter2" at address 21h
endc
;**************************************************************************
org 0x0000 ; Address of the first program instruction
banksel TRISB ; Selects bank containing register TRISB
clrf TRISB ; Clears TRISB
banksel PORTB ; Selects bank containing register PORTB
loop
movlw B'11110000' ; Binary number 11110000 is moved to W
movwf PORTB ; Number is moved to PORTB
movlw h'FF' ; Number hFF is moved to W
movwf counter2 ; Number is moved to variable "counter2"
loop2
movlw h'FF' ; Number hFF is moved to W
movwf counter1 ; Number is moved to "counter1"
loop1
decfsz counter1 ; Decrements "counter1" by 1. If result is 0
goto loop1 ; skip next instruction
decfsz counter2 ; Decrements "counter2" by 1. If result is 0
goto loop2 ; skip next instruction
movlw B'00001111' ; Binary number 00001111 is moved to W
movwf PORTB ; Number is moved to PORTB
movlw h'FF' ; Number hFF is moved to W
movwf counter2 ; Number is moved to variable "counter2"
loop4
movlw h'FF' ; Number hFF is moved to W
movwf counter1 ; Number is moved to variable "counter1"
loop3
decfsz counter1 ; Decrements "counter1" by 1. If result is 0
; skip next instruction
goto loop3
decfsz counter2 ; Decrements "counter2" by 1. If result is 0
goto loop4 ; skip next instruction
goto loop ; Jump to label loop
end ; End of program