;;Query the keyboard in an interrupt routine.
        ORG     100H        ;Tell the assembler to start at addr 0x100
START:  IM 1                ;Set interrupt mode 1
        LD      HL,GREET    ;Load the start address of the banner
        LD      B,15H       ;Set the length of the banner text
        LD      DE,0H       ;Start output in the top left corner
        CALL    84CDH       ;Call str_out
        HALT                ;Halts the CPU to save batteries.
        RET                 ;End the program
INTR:   IN      A,(16H)     ;Read the interrupt register
        AND     1H          ;Check if this is a keyboard interrupt
        RET     Z           ;Return if the bit was set
        CALL    8881H       ;Check the keycode of the pressed key
        CP      51H         ;Checks if the pressed key was "ON"
        JR      NZ,CNT      ;If the key was not "ON" continue
        LD      HL,EXIT     ;Load the exit marker
        LD      A,1H        ;Set the exit value to 1
        LD      (HL),A      ;Set the exit flag
        RET                 ;Return
CNT:    LD      HL,BUF      ;Load the buffer address
        CALL    BTOHEX      ;Convert the byte in A into a HEX-string and store it to BUF
        LD      B,2         ;Set the length for BUF
        LD      DE,15H      ;Position cursor at row 0, col 22
        CALL    84CDH       ;Print the keycode
        RET                 ;Return from INT
;;Convert the contents of A into a hex-string and stores the result in the buffer pointed in HL
BTOHEX: PUSH    AF          ;Store A onto the stack for later use
        LD      B,4         ;Init a loop for shifting the register
LP1:    SRL     A           ;Shift the MSN down to the least significant Nibble
        DJNZ    LP1         ;Shift again, until all 4 bits where shifted.
        CALL    HEXDGT      ;Converts the LSN to hex
        INC     HL          ;Point HL to the next byte in buffer
        POP     AF          ;Retrieve the original A
        AND     0FH         ;Cut the first digit of the hex no.
        CALL    HEXDGT      ;Call HEXDIGIT again for the second digit.
        LD      HL,BUF      ;Restore the buffer address
        RET
;;Converts the least significant nibble in A into a ASCII hex-digit and stores the result
HEXDGT: CP      0AH         ;Check if the number is smaller than 10
        JR      C,SKIP      ;Skip the next instruction, if it is
        ADD     A,07H       ;If the value is >10, we need to skip the chars between '9' and 'A'
SKIP:   ADD     A,30H       ;Converts the number into its ASCII digit
        LD      (HL),A      ;Store the digit in the correct location.
        RET        
GREET:  DB      'Test keyboard input: '
BUF:    DS      2           ;Define a 2 byte bufferto store the keycode in ASCII
EXIT:   DB      0           ;Sets the end marker in the code      
        END                 ;Signals the code end to the assembler
