Writing an Interrupt-Driven Keyboard Handler: VKEYBD, KBCODE and a Type-Ahead Buffer

Atari screen showing the hexadecimal key codes 3F 3E 3A 7F 0C 21 on one line

When you press a key, the Atari doesn't wait for the program to look. POKEY scans the keyboard itself, latches the key's code and raises an interrupt. A short OS routine then copies the code to location 764 (CH), where BASIC's GET and the screen editor find it. That routine is reached through a RAM vector, VKEYBD, so you can replace it. Reasons to do so include keeping more than one pending key, reacting the instant a key goes down, ignoring keys entirely, or remapping the keyboard.

What you'll learn: what POKEY reports, exactly what the OS keyboard interrupt routine does (from the original OS source), how debounce and auto-repeat work, and how to write and install your own handler safely.

What you need: MADS and an emulator. Reading the Keyboard, Console Keys and HELP covers the BASIC-level view (CH, GET from K:, CONSOL) that this guide builds on.

1. What POKEY gives you

Register Address Meaning
KBCODE $D209 (53769), read Code of the last key: bits 0–5 identify the key, bit 6 = SHIFT, bit 7 = CTRL
SKSTAT $D20F (53775), read Bit 2 reads 0 while a key is still held; bit 3 reads 0 while SHIFT is held
IRQEN $D20E (53774), write Bit 6 enables the keyboard interrupt (shadow: POKMSK at $10)

Key codes are not ATASCII. They follow the keyboard matrix. Our test handler recorded 3F for A, 3E for S, 3A for D, 7F for SHIFT-A (the same key with bit 6 set), 0C for RETURN and 21 for the space bar. BREAK, START, SELECT, OPTION and RESET produce no key code at all. BREAK has its own interrupt, and the console keys are read from CONSOL.

2. What the OS handler does

The original OS keyboard routine sits at $FFBE, and VKEYBD ($0208) points there at power-up. In the June 1979 OS source it does this, in order:

  1. Read KBCODE and compare it with CH1 ($02F2), the last key accepted. If it is the same key and the debounce counter KEYDEL ($02F1) is not yet zero, ignore it as switch bounce.
  2. If the key is CTRL-1, flip the start/stop flag SSFLAG ($02FF), which pauses screen output, and don't pass the key on.
  3. Otherwise store the code in CH ($02FC) and in CH1, set KEYDEL to 3, and clear ATRACT ($4D), so a key press ends attract-mode colour cycling.
  4. Set the software repeat timer SRTIMR ($022B) to $30 (48 frames, about 0.8 seconds on NTSC).
  5. PLA and RTI.

Auto-repeat is not done in the interrupt at all. The stage-2 vertical-blank routine checks SKSTAT bit 2. While the key stays down it counts SRTIMR down, and when it reaches zero it reloads it with 6 and copies KBCODE straight into CH. Repeats therefore bypass VKEYBD, and a replacement handler sees only the first press of a held key. KEYDEL is counted down in the same VBI code, but only while no key is held.

3. Rules for your own handler

The OS IRQ dispatcher has already pushed the accumulator before it jumps through VKEYBD. Your routine must:

  • save and restore X and Y if it uses them,
  • finish with PLA and RTI, never RTS,
  • be short. Other interrupts (serial I/O, timers) wait while it runs,
  • swap the vector with interrupts disabled (SEI ... CLI), so a key press can't arrive while only one byte of the vector has changed.

You don't need to acknowledge the interrupt in IRQEN: the OS dispatcher does that before calling you. Keep the old vector, so you can restore it, or chain to the OS routine when you want normal behaviour too.

4. A type-ahead buffer

The OS keeps only one pending key in CH. A fast typist, or a program busy for a moment, loses keystrokes. This handler puts every key code into a 16-entry ring buffer instead. The main loop takes codes out in order and shows them in hexadecimal on the screen:

; Interrupt-driven keyboard handler with a 16-key type-ahead buffer
VKEYBD  = $0208
KBCODE  = $D209
SKSTAT  = $D20F
SAVMSC  = $58
ATRACT  = $4D
CH      = $02FC

        org $3000

start   sei                 ; swap the vector with IRQs off
        lda VKEYBD
        sta oldkey
        lda VKEYBD+1
        sta oldkey+1
        lda #<keyirq
        sta VKEYBD
        lda #>keyirq
        sta VKEYBD+1
        cli

; main loop: take keys out of the buffer and show their codes in hex
main    ldx tail
        cpx head            ; buffer empty?
        beq main
        lda buf,x           ; fetch the oldest key
        pha
        inx
        txa
        and #15             ; 16-entry ring
        sta tail
        pla
        jsr showhex
        jmp main

; --- the interrupt handler (entered with A already pushed by the OS) ---
keyirq  txa                 ; save X
        pha
        lda KBCODE          ; key code + SHIFT (bit 6) + CTRL (bit 7)
        ldx head
        sta buf,x           ; store at the head
        inx
        txa
        and #15
        cmp tail            ; full? then drop the key
        beq full
        sta head
full    lda #0
        sta ATRACT          ; a key press cancels attract mode
        pla                 ; restore X
        tax
        pla                 ; restore A (pushed by the OS dispatcher)
        rti

; print A as two hex digits at the next position on screen row 3
showhex pha
        lsr
        lsr
        lsr
        lsr
        jsr digit
        pla
        and #15
        jsr digit
        inc col             ; leave a gap
        rts
digit   tax
        lda hexd,x
        pha
        clc
        lda SAVMSC
        adc #120
        sta $CB
        lda SAVMSC+1
        adc #0
        sta $CC
        ldy col
        pla
        sta ($CB),y
        inc col
        rts

hexd    dta d'0123456789ABCDEF'
oldkey  dta a(0)
head    dta 0
tail    dta 0
col     dta 2
buf     :16 dta 0

        run start

How it works:

  • head is where the interrupt writes and tail is where the main loop reads. They are equal when the buffer is empty. The handler stores the key first and only advances head if that would not make it equal to tail, so a full buffer drops new keys instead of overwriting old ones.
  • Only the handler changes head and only the main loop changes tail, so the two never need to disable interrupts to share the buffer.
  • The handler doesn't debounce. On real keyboards you may want the OS's approach: ignore a repeat of the same code until a frame or two has passed.

Assemble with mads kbd.asm -o:kbd.xex and run it. In our test, typing A, S, D, SHIFT-A, RETURN and SPACE produced 3F 3E 3A 7F 0C 21. To turn the codes into characters, look them up in a 64-entry table per shift state, which is exactly what the OS's own table does (see ATASCII and Keyboard Codes).

5. Other things you can do in VKEYBD

  • Game controls on the keyboard. Set a flag or a direction byte the moment a key goes down, and use SKSTAT bit 2 in your VBI to see when it is released. The OS's CH only tells you that a key was pressed at some point.
  • Hotkeys. Check for one code (say CTRL-P for pause) and act on it, then JMP to the saved old vector so every other key behaves normally. Jumping to the old routine is safe because A is still pushed, exactly as the OS routine expects.
  • Silence the keyboard. Clear bit 6 in both POKMSK and IRQEN and no keyboard interrupts happen at all. BREAK has its own bit (bit 7) in the same registers.
  • Remap without a handler (XL/XE). The XL OS converts codes using a 192-byte table pointed to by KEYDEF at $79–$7A (121–122): 64 bytes each for unshifted, SHIFT and CTRL. Point it at your own copy to change what keys produce.
  • BREAK. It isn't seen by VKEYBD. The OS sets BRKKEY ($11) to 0 when BREAK is pressed. On OS revision B and the XL/XE there is a separate vector, BRKKY at $0236.

Troubleshooting

  • Machine hangs at the first key press: the handler ended with RTS, or forgot the final PLA, so the stack is wrong.
  • Random crashes while typing: the handler changed X or Y without restoring them, or the vector was changed with interrupts enabled.
  • Held keys don't repeat: expected. Repeats are injected into CH by the VBI, not through VKEYBD. Either implement your own repeat with SKSTAT and a timer, or chain to the OS routine and read CH.
  • BASIC's GET or INPUT stops working: your handler no longer writes CH. Chain to the old vector, or store the code in CH yourself.
  • Keys double up on real hardware: add debounce (compare with the previous code and require a short delay).

Further reading

  • Atari, Inc., Atari 400/800 Operating System Source Listing (1981): the keyboard IRQ routine at $FFBE and the stage-2 VBI repeat logic.
  • Ian Chadwick, Mapping the Atari: 520 (VKEYBD), 555 (SRTIMR), 753–754 (KEYDEL, CH1), 764 (CH), 53769 (KBCODE) and 53775 (SKSTAT).
  • Atari, Inc., Operating System User's Manual: interrupt processing and the IRQ vector table.
  • On this site: Reading the Keyboard, Console Keys and HELP, Vertical Blank Interrupts, ATASCII and Keyboard Codes.

Credits