Program Loops (DJNZ)

16.11 Program Loops (DJNZ)

Many operations are conducted within finite loops. That is, a given code seg- ment is executed repeatedly until a given condition is met.

A common type of loop is a simple counter loop. This is a code segment that is executed a certain number of times and then finishes. This is accomplished easily in 8052 assembly language with the DJNZ instruction. DJNZ means decrement, jump if not zero. Consider the following code:

MOV R0,#08h ;Set number of loop cycles to 8

LOOP: INC A ;Increment accumulator (or do whatever ;the loop does)

DJNZ R0,LOOP ;Decrement R0, loop back to LOOP if R0 ;is not 0

DEC A ;Decrement accumulator (or whatever you ;want to do)

This is a very simple counter loop. The first line initializes R0 to 8, which is the number of times the loop will be executed.

The second line labeled LOOP, is the actual body of the loop. This could con- tain any instruction or instructions you wishe to execute repeatedly. In this case, the accumulator is incremented with the INC A instruction.

The interesting part is the third line with the DJNZ instruction. This instruction says to decrement the R0 Register, and if it is not now zero, jump back to LOOP. This instruction decrements the R0 register, then checks to see if the new value is zero and, if not, will go back to LOOP. The first time this loop exe- cutes, R0 is decremented from 08 to 07, then from 07 to 06, and so on until it decrements from 01 to 00. At that point, the DJNZ instruction fails because the accumulator is zero. That causes the program to not go back to LOOP, and thus, it continues executing with the DEC instruction—or whatever you want the program to do after the loop is complete.

DJNZ is one of the most common ways to perform programming loops that ex- ecute a specific number of times. The number of times the loop is executed depends on the initial value of the R register that is used by the DJNZ instruc- tion.

16-12

Page 206
Image 206
Texas Instruments MSC1210 manual Program Loops Djnz