Wednesday, March 23, 2016

8051 Loop

In the 8051, the loop action is performed by the instruction “DJNZ Rn, LABEL”. In this instruction, the register is decremented; if it is not zero, it jumps to the target address referred to by the label. Prior to the start of the loop the register is loaded with the counter for the number of repetitions.

Register is used as a counter. RAM location can also be used as counter as in “DJNZ direct address, LABEL”.

Program to add value 5 to ACC 12 times.

ORG 0H
MOV A, #0 ; Clear accumulator
MOV R4, #12 ; Initialize counter
LOOP :ADD A, #5; Add 5 to accumulator
DJNZ R4, LOOP ; Repeat until R4 = 0
END


Since register or memory location is 8 bit, it can hold a maximum of FFH (255 decimal); therefore, the loop can be repeated a maximum of 256 times. In order to repeat the loop more than 256 times, nested loop is used.

Program to add value 5 to ACC 1200 times.

ORG 0H
MOV A, #0 ; Clear accumulator
MOV R4, #12 ; Initialize outer loop counter
OUTLOOP :MOV R5, #100 ; Initialize inner loop counter
INLOOP : ADD A, #5; Add 5 to accumulator
DJNZ R5, INLOOP ; Repeat until R5 = 0
DJNZ R4, OUTLOOP ; Repeat until R4 = 0
END


Infinite Loop:
ORG 0H
HERE : SJMP HERE
END


A simple way of doing that is to use the $ sign.
ORG 0H
SJMP $
END



Related topics:
8051 Delay   |   8051 IO Port Programming   |   8051 Timer Programming   |   8051 Counter   |   8051 Serial Port Programming   |   8051 Programming Timer Interrupt   |   8051 Programming Serial Interrupt   |   8051 Programming External Interrupt

List of topics: 8051

No comments:

Post a Comment