← r0mheat z80 lessons: all projects

Z80 assembly: How a CPU runs code

Follow the Program Counter as the CPU fetches, decodes and executes five 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. The brackets in LD HL,(value2) mean the content of memory at that address. There is no new opcode in this lesson.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

The program starts at 0100h. Its four instructions and HALT occupy 11 bytes (0100h to 010Ah). DB places the byte 42h after the code, at 010Bh. DW places the 16-bit word 1234h at 010Ch. The low byte 34h comes first.

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 010Bh, value2 at 010Ch

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
Four LD instructions3E 05 06 03 21 0B 01 2A 0C 0110 bytes40 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.
DWDefine WordAssembler directive, not an instruction. Places a 16-bit word in memory, low byte first.
DBDefine ByteAssembler directive, not an instruction. Places a byte in memory.