'-------------------------------------------------------------------------------
Sub Main()

' This program will read a 4 x 4 matrix keypad connected to the PORTA pins.
' A byte value is displayed based in the key pressed.

    Dim KeypadValue As Byte
    Dim Vertical As Byte
    Dim Horizontal As Byte

    Call OpenSerialPort(1, 19200)
    
    Do
        ' Set up PORTA to read horizontal keys:
        '    Set bits A0 .. A3 (LSNybble) to input-pullup -- horizontal.
        '    Set bits A4 .. A7 (MSNybble) to output-low   -- vertical.
        Register.DDRA  = bx1111_0000
        Register.PORTA = bx0000_1111
        
        ' If a key is pressed, store its value. Then do the same with the
        ' vertical keys
        If (Register.PINA <> bx0000_1111) Then

            Horizontal = Register.PINA   ' LSNybble

            ' Set up PORTA to read vertical keys:
            '    Set bits A0 .. A3 (LSNybble) to output-low   -- horizontal.
            '    Set bits A4 .. A7 (MSNybble) to input-pullup -- vertical.
            Register.DDRA  = bx0000_1111
            Register.PORTA = bx1111_0000

            Vertical = Register.PINA     ' MSNybble
            
            ' Combine horizontal and vertical nybbles.
            KeypadValue = Vertical Or Horizontal
            
            ' Debounce.
            Call Delay(0.2)
            
            ' Display data.
            Call PutB(KeypadValue)
            Call NewLine

            Call WaitForKeyRelease
        End If
    Loop

End Sub
'-------------------------------------------------------------------------------
Sub WaitForKeyRelease()

    Do
    Loop Until (Register.PINA = bx1111_0000)

End Sub
'-------------------------------------------------------------------------------
' Pin numbering:
'
' PORTA
'  BIT    BX-01   BX-24
'
'  A7      32      13
'  A6      33      14
'  A5      34      15
'  A4      35      16
'  A3      36      17
'  A2      37      18
'  A1      38      19
'  A0      39      20
'-------------------------------------------------------------------------------
