# Skill: CIA I/O, Timers, Keyboard, Joystick, Serial Bus, and User Port ## Use this skill when The task involves CIA chips, keyboard scanning, joysticks, timers, real-time clock, serial bus, disk/printer handshaking, RS-232, or user port I/O. ## CIA bases | Chip | Decimal | Hex | Common role | |---|---:|---:|---| | CIA #1 | 56320 | `$DC00` | Keyboard matrix, joystick ports, timers, TOD, IRQ | | CIA #2 | 56576 | `$DD00` | Serial bus, RS-232/user port, VIC bank select, NMI | ## CIA register layout Each CIA exposes 16 registers mirrored across its 256-byte block. | Offset | Purpose | |---:|---| | 0 | Port A data | | 1 | Port B data | | 2 | Port A data direction | | 3 | Port B data direction | | 4-5 | Timer A latch/counter low/high | | 6-7 | Timer B latch/counter low/high | | 8-11 | Time-of-day clock | | 12 | Serial data register | | 13 | Interrupt control/status | | 14 | Control register A | | 15 | Control register B | ## Joystick reading Joystick values are active low. - Port 2 commonly read at `$DC00` / `56320`. - Port 1 commonly read at `$DC01` / `56321`. Typical bits: | Bit | Mask | Direction/button | |---:|---:|---| | 0 | 1 | Up | | 1 | 2 | Down | | 2 | 4 | Left | | 3 | 8 | Right | | 4 | 16 | Fire | Pressed means bit is `0`. BASIC example: ```basic 10 J=PEEK(56320) 20 IF (J AND 16)=0 THEN PRINT "FIRE" ``` ## Serial bus concepts - Device numbers distinguish serial devices. - The C64 sends ATN, then TALK or LISTEN, plus optional secondary address. - Data is transferred one byte at a time using handshaking. - Prefer KERNAL routines (`SETLFS`, `SETNAM`, `OPEN`, `CHRIN`, `CHROUT`, `CLOSE`) unless bit-banging is the task. ## Timer principles - CIA timers can count CPU cycles or external CNT pulses. - Timer underflow can generate interrupts. - For reliable timing, acknowledge CIA interrupt source and avoid leaving stale flags. ## Agent checklist 1. Identify CIA #1 vs CIA #2. 2. Preserve data direction registers unless intentionally changing port direction. 3. Remember joystick and keyboard are active-low. 4. For serial/disk/printer, prefer KERNAL I/O. 5. For timers, show latch, control, interrupt enable, and acknowledge steps.