← r0mheat z80 lessons: all projects

Z80 assembly: DJNZ

The counted loop. One instruction decrements B and jumps back until B reaches zero.

DJNZ e10FCDecrement B, Jump if Not Zero
  • B ← B − 1
  • if B ≠ 0: PC ← PC + e (jump, 13 T-states)
  • if B = 0: continue (8 T-states)
  • flags: none change

The second byte, e, is a signed displacement. It is added to the address after DJNZ. Here, FCh (−4) at 0106h gives 0108h − 4 = 0104h.

Loop passes (starting value of B)
Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The loop adds 3 to A once per pass. Registers start at 0. The highlighted row is at PC. Each Step executes one instruction fetched from memory.

Registers and flags

Flags

A register is a small storage place in the CPU. PC means Program Counter. A T-state is one CPU clock period. A flag records a result from an instruction. S is sign, Z is zero, H is half-carry, P/V is parity or overflow, N is add/subtract, and C is carry. This page ignores undocumented X and Y bits.

Execution trace

#AddressInstructionResultT-states

DJNZ compared with two instructions

; use B as the loop counter
loop:  DEC B
       JR NZ,loop
Loop controlDJNZDEC B + JR NZ

DEC B changes S, Z, H, P/V and N. DJNZ changes no flags. The timing counts here cover loop control only.

Mnemonic glossary

Program mnemonics
MnemonicStands forWhat it does here
LDLoadLoads a value into a register.
ADDAddAdds 3 to A and updates all six documented flags.
DJNZDecrement B, Jump if Not ZeroSubtracts 1 from B. It jumps back if B is not 0. It does not change flags.
HALTHaltStops this lesson’s CPU until reset. Interrupts are not modeled.
ORGOriginAssembler directive, not a CPU instruction. Places the COM-style program at 0100h.