The Drawback of Main Loop Polling

In simple programs, checking the keyboard (`IN′ instruction) is done within the main program loop. This is inefficient because the CPU spends valuable time polling the keyboard even when no key is pressed, slowing down the main application.

The Solution: Timer-Driven Interrupts A robust operating system uses a fixed-rate timer interrupt (e.g., 50 or 60 times per second) to trigger the keyboard scan routine. This ensures the keyboard is checked reliably without interfering with the main application’s logic.

The Keyboard Interrupt Service Routine (ISR)

This routine is executed quickly every time the timer fires. Its job is minimal: scan one row, store the result, and get out.

The ISR Logic:

TIMER_KEYBOARD_ISR:
    DI                    ; Disable global interrupts
    PUSH AF, BC           ; Save only necessary registers
    
    ; 1. Load the I/O port address into C and the row strobe value into A
    CALL GET_NEXT_ROW_MASK ; Routine to load A/C with next row's I/O data
    
    ; 2. Strobe the I/O port to select the row
    OUT  (C), A
    
    ; 3. Read the key status back into A
    IN   A, (C)
    
    ; 4. Store the raw key status byte in a dedicated memory buffer
    LD   (HL), A           ; HL points to the buffer where row status is saved
    
    ; 5. Advance to the next row for the next interrupt cycle
    CALL ADVANCE_SCAN_POINTER
    
    POP  BC, AF
    EI                    ; Re-enable global interrupts
    RETI                  ; Return from interrupt

The Key Buffer (Debouncing and FIFO)

The ISR quickly stores the raw key status bytes into a temporary Key Status Buffer in RAM (e.g., 8 bytes for 8 rows). The main OS kernel routine (`CHECK_KEYBOARD′ in the main loop) then reads from this buffer when needed.

Debouncing: The kernel also handles key debouncing (checking if a key is held down or if a contact bounce causes false presses) by comparing the current key status byte with the status from the previous frame.

Final Output: The FIFO Buffer

The final, filtered keypresses are stored in a FIFO (First-In, First-Out) Buffer.

User Program Access: When a user program needs input (e.g., waiting for a character), it makes an OS system call. The kernel reads the next available character from the FIFO buffer and passes it back to the user program. If the buffer is empty, the program waits (`HALT′ instruction) until the next interrupt fills the buffer.