LAB 6 Loop Instructions
LAB 6 Loop Instructions
INSTRUCTION SET
© Dr J.Iqbal
© Dr J.Iqbal
© Dr J.Iqbal
© Dr J.Iqbal
LAB 6
LOOPS IN ASSEMBLY
LOOPS
Repeating a sequence of instructions a certain
number of times is called a loop
In the 8051, the loop is performed mostly by the
instruction
ORG 0
MOV R0, #20h ; initialize R0
MOV R1, #40h ; initialize R1
MOV R2, #11h ; initialize R2 as
; counter
LOOP1:
MOV A, @R0 ; read DATA
MOV @R1, A ; write DATA
INC R0
INC R1
DJNZ R2, LOOP1
LOOPS USING COMPARE INSTRUCTION
CJNE dest-byte, scr-byte, rel-address
; (Compare and jump if not equal)This instruction
compares dest-byte and scr-byte and jump to rel-
address if they are not equal
ORG 0
MOV P0, #0FFh ; make P0 input port
START:
MOV A, P0 ; scan/ read P0
CJNE A, #0FFh, MULT ; compare with 0FFh
SJMP START ; jump to scan again
MULT:
MOV B, #10 ;
MUL AB ; multiply with 10
MOV P1, A ; send low byte to P1
MOV P2, B ; send high byte to P2
SJMP START
EXERCISE
Write a program that finds the position of the first high in
an 8-bit data item and display the result on P0. The data
is scanned from D7 to D0. Give the result for 68H
ORG 0
MOV A, #68h ; Let A = 68h
MOV R0, #8 ; initialize counter
AGAIN:
RLC A ; rotate left through carry
JC FND ; if MSB = 1, jump to FND
DJNZ R0, AGAIN ; repeat
MOV P0, R0 ; ‘1’ not found
SJMP $ ; stay here
FND:
MOV P0, R0 ; ‘1’ found, display its position
SJMP $
END
NESTED LOOPS
MOV A, #0
for(i = 0; i<1000; i++)
MOV R0, #4
{
LOOP1:
a = a+2;
MOV R1, #250
}
LOOP2:
ADD A, #2
As
DJNZ R1, LOOP2
1000/255 = 3.92
DJNZ R0, LOOP1
We take
END
1000/250 = 4
NESTED LOOPS- EXERCISE
Write a program to implement following C code in
assembly
org 00
mov dptr,#200h
cont: mov a,#00
movc a,@A+dptr
jz exit
inc dptr
cjne a,#‘g',cont
exit: mov r1,a
jmp $
org 200h
string: db "hello gee“,0
END
LOOK-UP TABLE - EXERCISE
Write a program to add the following numbers and send the result to P1
and P2. The data is stored at ROM addresses starting from 250H
(53, 49, 94, 56, 92, 65, 43, 83)
ORG 0 NEXT:
MOV DPTR, #mydata INC DPTR
MOV R2, #8 DJNZ R2, AGAIN
MOV P1, R3
AGAIN:
MOV P2, R7
CLR A
SJMP $
MOVC A, @A+DPTR
ADD A, R3
ORG 250H
MOV R3, A
MYDATA: DB 53,
JNC NEXT 49, 94, 56, 92, 65, 43, 83
INC R7 END