The Keyboard Matrix Scan

Unlike modern PCs, Z80 systems don’t receive ASCII codes from the keyboard. Instead, the keyboard is wired as a matrix of rows and columns. To detect a keypress, the Z80 must scan this matrix using its I/O ports.

The Two-Step Process:

  1. Output (Strobe): The CPU writes a value to an I/O port to select (or “strobe”) a single row of the keyboard matrix.
  2. Input (Read): The CPU reads a value from another I/O port. The bits set to ‘1’ in the input byte indicate which keys in the selected row are currently being pressed.

Example: Scanning a Single Row

Let’s assume our target system uses I/O port FEH for both output (strobe) and input (read) and that the rows are addressed by setting one bit to ‘0’.

Goal: Read keys on Row 4 (e.g., keys A, S, D, F, G).

ROW_FOUR_MASK EQU 0DFH      ; The value to strobe Row 4 (0DFH = 11011111b)
KEYBOARD_PORT EQU 0FEH      ; The I/O port address

SCAN_ROW_4:
    LD   A, ROW_FOUR_MASK   ; A = Strobe mask for Row 4
    OUT  (KEYBOARD_PORT), A ; Output the mask to select the row
    
    IN   A, (KEYBOARD_PORT) ; Read the status of the keys on that row back into A
    
    ; The Accumulator (A) now holds the status for keys A, S, D, F, G, etc.
    RET

Interpreting the Input Byte

The value returned in the Accumulator (A) is a combination of bits representing the five or eight keys on that row.

Checking for a Specific Key: You use the BIT instruction and the Z (Zero) flag to check if a specific key’s bit is set.

Example: Checking the ‘A’ key (Bit 0)

    ; ... (After SCAN_ROW_4 completes)
    
    BIT  0, A               ; Check if the bit for key 'A' is 0 (pressed)
    JP   Z, A_KEY_PRESSED   ; Z=1 means the key's bit is low (pressed on many systems)
    
    ; If the jump is not taken, the key is not pressed.

The Full Keyboard Scan

To check the entire keyboard, the program must run the two-step process (strobe and read) for every single row of the keyboard matrix sequentially. This routine runs hundreds of times per second to provide responsive input.