Level 23: Gamepad

Open the level →Where it fits in the machine →

Task

Goal: Write a program that reads the gamepad (port 254) and stores the value in RAM[0].

The Gamepad is connected to the data bus and accessible via port 254 (0xFE).

The main idea: the outside world is just another address: to the program the gamepad looks like a cell at address 254, and LDA 254 reads the buttons the same way it reads memory. One instruction serves both memory and input.

Related Materials

Solution for self-check

Try building the circuit yourself first. The solution below is a way to check yourself if you're stuck or have already solved it.

What you should get: after Run and the checkpoint, RAM[0] = 5 (Up + Left pressed).

Notice that the processor is being deceived: ADD 254 looks like a memory read, and the CPU is "sure" it is reading RAM. But address 254 lies in the I/O zone (224–255) — the address decoder physically intercepts the access and substitutes the gamepad data. The CPU never suspects it is talking to a device.

Key distinction: - LDA N loads the IMMEDIATE value N (a number). - ADD N reads data FROM ADDRESS N on the bus and adds it to the accumulator.

To read the gamepad: 1. LDA 0 — clear the accumulator (Acc = 0) 2. ADD 254 — Acc = 0 + gamepad = button state 3. STA 0 — store in RAM[0] 4. HLT

Gamepad buttons (bits): - Bit 0 (1): Up - Bit 1 (2): Down - Bit 2 (4): Left - Bit 3 (8): Right

The checkpoint sets buttons = 5 (Up + Left) and checks RAM[0] = 5.

Click "Run", then "Checkpoint".

Assembler help →

Check yourself

How does LDA 254 differ from ADD 254?

LDA loads the immediate number 254; ADD reads the data at address 254 from the bus — the gamepad buttons.