DYSTOPIANPIXEL

What the CPU does

Follow the fetch, decode and execute cycle, and distinguish the assembler from the processor.

Next Asset Lab concept artwork showing sprite patterns, palette colours and animation frames
Next Asset Lab concept artwork · Begin with Odin Dev.2k and the foundations of Z80 assembly.
TUTORIAL 1 / PART 02

What the CPU actually does

Before learning number systems or registers, it helps to have a simple picture of what the processor is doing. The Z80 is the CPU — the central processing unit. It repeatedly reads instructions from memory and carries them out.

The fetch–decode–execute cycle

A useful beginner model is a three-step cycle: fetch an instruction from memory, decode what that instruction means, then execute it. After that, the CPU continues with the next instruction unless the current instruction changes the flow.

1. FETCH    Read the next instruction byte or bytes from memory
2. DECODE   Work out which Z80 instruction those bytes represent
3. EXECUTE  Perform the operation
4. REPEAT

This happens extremely quickly, but the same basic idea applies whether the instruction is loading a register, adding two values, jumping somewhere else in the program or returning from a routine.

The CPU does not read our assembly source

When we type LD A,$42, the Z80 does not see the letters L and D. Odin, the assembler, translates our readable source into machine-code bytes. Those bytes are placed in memory. The CPU fetches and executes the bytes.

  1. assembly source ld a,$42
  2. Odin assembler
  3. machine-code bytes 3E 42
  4. stored in memory
  5. Z80 fetches and executes those bytes

The Program Counter: where is the CPU executing?

The CPU needs to remember where it is in the program. The 16-bit PC register — the Program Counter — contains the address of the next instruction the processor is working through. Normally the CPU advances PC automatically as instruction bytes are consumed.

PC = $6000   fetch instruction at $6000
             instruction occupies some number of bytes
PC advances to the address of the following instruction

Later in this tutorial we will see our own program assembled at $6000. At that point this idea becomes concrete: $6000 is not merely a number on the screen; it is an address from which the processor can fetch instruction bytes.