Z80 assembly: How a CPU runs code
Follow the Program Counter as the CPU fetches, decodes and executes five instructions.
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.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
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
| # | Address | Instruction | PC after | T-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 part | Bytes | Code size | CPU time |
|---|---|---|---|
| Four LD instructions | 3E 05 06 03 21 0B 01 2A 0C 01 | 10 bytes | 40 T-states |
| HALT | 76 | 1 byte | 4 T-states |
Simplification: this lesson has one 64 KB memory and no interrupts or input/output devices.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | What it does here |
|---|---|---|
| LD | Load | Copies a number into a register. |
| HALT | Halt | Stops this lesson’s CPU. Interrupts are not modeled. |
| ORG | Origin | Assembler directive, not an instruction. Sets the code address. |
| DW | Define Word | Assembler directive, not an instruction. Places a 16-bit word in memory, low byte first. |
| DB | Define Byte | Assembler directive, not an instruction. Places a byte in memory. |