liveBook · Manning

CHIP-8 keypad

As explained in Systems Programming with Zig

The CHIP-8 keypad is the virtual machine's 16-key input interface.

The CHIP-8 keypad is a 16-key input interface. A practical desktop mapping assigns its keys to the number pad, whose layout resembles the COSMAC VIP keypad, with Q, W, E, and R filling the remaining positions. section 6.4.3

Store the 16 Raylib key codes in an array, then update the virtual machine’s keypad by checking IsKeyPressed for each code every frame. Drawing a square for each pressed key makes the mapping visible. section 6.4.3

CHIP-8’s FX0A instruction waits for a key press and puts the first pressed key’s hexadecimal value in register X. If no key is pressed, the interpreter can repeat the instruction by subtracting two from the program counter; it should also clear the keypad state to avoid reusing an input. section 6.5.7

Listing 6.12 The key to the keypad
const vm = @import("vm"); #1

const c = @cImport({
    @cInclude("raylib.h");
});

const keypad_keys = [16]c_int{ #2
    c.KEY_KP_0, c.KEY_KP_1, c.KEY_KP_2,   c.KEY_KP_3,
    c.KEY_KP_4, c.KEY_KP_5, c.KEY_KP_6,   c.KEY_KP_7,
    c.KEY_KP_8, c.KEY_KP_9, c.KEY_KP_ADD, c.KEY_KP_ENTER,
    c.KEY_Q,    c.KEY_W,    c.KEY_E,      c.KEY_R,
};

pub fn main() !void {
    var keypad: vm.Keypad = undefined; #3

    c.InitWindow(640, 480, "CHIP-8"); #4
    defer c.CloseWindow();

    c.SetTargetFPS(60);

    while (!c.WindowShouldClose()) {
        for (keypad_keys, 0..) |key, i| {
            keypad.keys[i] = c.IsKeyPressed(key); #5
        }

        c.BeginDrawing();
        defer c.EndDrawing();

        c.ClearBackground(c.BLACK);

        for (keypad.keys, 0..) |is_pressed, i| {
            if (!is_pressed) continue;
            const x: c_int = @intCast(i * 20);
            c.DrawRectangle(x, 0, 20, 20, c.WHITE); #6
        }
    }
}

See the Raylib mapping array, per-frame keypad update, and on-screen pressed-key indicator. section 6.4.3

How Systems Programming with Zig covers it

How deep it goes
Implements key mapping and polling, then describes FX0A handling; it leaves the remaining interpreter work to the reader.
Examples
Maps the number pad and QWER to keys, polls them with IsKeyPressed, and displays pressed keys as white squares.
What you can do after
Apply it via Raylib to map desktop key presses into a virtual machine keypad and display their state.
How it connects
Connects to Raylib input polling, CHIP-8 instruction FX0A, the program counter, and registers.

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.