Z80 assembly: How a CPU runs code

Follow the Program Counter as the CPU fetches, decodes and executes four instructions.

Fetch → decode → executeOne Step runs one instruction

The CPU reads the byte at PC, understands its instruction, and performs it. Then PC points to the next instruction. This example uses LD and HALT. There is no new opcode in this lesson.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program starts at 0100h. Its three instructions and HALT occupy 8 bytes. DB places 42h immediately after the code at 0108h.

Registers, flags and memory

Flags

A register stores a small value inside the CPU. PC means Program Counter. A T-state is one CPU clock period. A flag records a result. LD and HALT do not change flags in this example. This page ignores undocumented X and Y bits.

Sample data memory value at 0108h

Execution trace

#AddressInstructionPC afterT-states

Assembly and machine code

Assembly uses short names called mnemonics. The bytes in the second column are the machine code that the CPU fetches.

Program partBytesCode sizeCPU time
Three LD instructions3E 05 06 03 21 08 017 bytes24 T-states
HALT761 byte4 T-states

Simplification: this lesson has one 64 KB memory and no interrupts or input/output devices.

Mnemonic glossary

Program mnemonics and directives
NameStands forWhat it does here
LDLoadCopies a number into a register.
HALTHaltStops this lesson’s CPU. Interrupts are not modeled.
ORGOriginAssembler directive, not an instruction. Sets the code address.
DBDefine ByteAssembler directive, not an instruction. Places a byte in memory.