228. Cpu bus ppu register read routing

Route CpuBus reads from $2000-$3FFF to PPU registers.

Lesson 228 of 356 · tests/chapter_03_ppu_memory_and_graphics_data/test_228_cpu_bus_ppu_register_read_routing.py

File to update

emulator/bus/cpu_bus.py

Why this step exists

The CPU sees PPU registers through the CPU address map

$2000-$3FFF -> PPU registers, mirrored every 8 bytes

Only $2000-$2007 are the base PPU register addresses. The rest of the range is mirrors of those same 8 registers.

Mirroring formula

unmirrored_addr = 0x2000 + ((addr - 0x2000) % 8)

How it works

1. addr - 0x2000 converts the CPU address into an offset from the start of
   the PPU register window.
2. % 8 folds that offset into the repeating 8-register range.
3. + 0x2000 converts the folded offset back into a base PPU register address.

Examples

$2002:
    0x2000 + ((0x2002 - 0x2000) % 8)
    = 0x2000 + (2 % 8)
    = $2002

$200A:
    0x2000 + ((0x200A - 0x2000) % 8)
    = 0x2000 + (10 % 8)
    = $2002

$3FFF:
    0x2000 + ((0x3FFF - 0x2000) % 8)
    = 0x2000 + (8191 % 8)
    = $2007

Why CpuBus owns the formula

Mirroring is CPU address-map decoding. PPU.read_register should receive a normalized register address in $2000-$2007.

Suggested implementation pseudocode

if 0x2000 <= addr <= 0x3FFF:
    unmirrored_addr = 0x2000 + ((addr - 0x2000) % 8)
    return self.ppu.read_register(unmirrored_addr)

Run this lesson

uv run pytest tests/chapter_03_ppu_memory_and_graphics_data/test_228_cpu_bus_ppu_register_read_routing.py -v