Reputation: 91
I have couple of examples which are pretty simple except LABEL concept. Example 1 adds 25 10 times in itself, whereas example 2 takes complement of Register A 700 times.
Example-1: MOV A,#0
MOV R2,#10
AGAIN: ADD A,#25
DJNZ R2,AGAIN
MOV R5,A
Example-2:
MOV A,#55H
MOV R3,#10
NEXT: MOV R2,#70
AGAIN: CPL A
DJNZ R2,AGAIN
DJNZ R3,NEXT
I am unable to understand the concept of LABEL. In example-1, when first time program runs, A gets value 25, and then when R2 decrements from 10 to 1, output is 275 instead of 250. But if I assume that LABEL is bypassed unless it is called, then things are ok and I get result 250. But if I assume the same thing (bypassing the LABEL in step by step execution) in Example-2, then LABEL NEXT will be bypassed. And "DJNZ R2,AGAIN" will be executed. As NEXT was bypassed, then how will R2 get the value #70? So my question is about execution of LABEL. Are the LABELS executed or bypassed?
Upvotes: 1
Views: 26239
Reputation: 39
Label is not bypassed. If you take a look at working of a loop then u will see that first DJNZ decrements the value of register then if the result is non zero it executes the label. In 1st example, starting from above:
1) A gets zero, then
2) R2 gets 10, then
3) A gets 25, then
4) DJNZ decrements the value of R2 making it 9 and since the result is non zero, executes AGAIN and it adds 25 in A making it 50 and so on.
When the value of R2 reaches 1, DJNZ decrements it and the result is zero so it won't execute AGAIN. Consequently, DJNZ is executed 9 times hence making result 25*9=225. But as 25 was stored in A before the execution of loop DJNZ, the result is 250. Hope It helps you.
Upvotes: 0
Reputation: 36649
and when 10 times DJNZ adds 25 in A it should come out to be 275
No, 250 is the correct answer. After the 10th add instruction, register R2
still contains 1
- it then gets decremented to 0 and then the DJNZ instruction does not jump to the label anymore, but skips to the following instruction.
You can regard DJNZ
as two instructions, similar to
DEC R2
JNZ AGAIN ; NOTE: 8051 does not have a Zero flag - would need to
; use ACC for that, so treat this as pseudo code!
You can use a simulator like http://www.edsim51.com/ to step through the instructions and watch how the registers change for each step. That is very useful for learning how specific instructions behave.
Upvotes: 1