Device 16F877 ' Define what device your using
XTAL = 4 ' Set the Osc speed
Symbol KeypadTris = TRISC
Symbol KeypadPort = PORTC
Dim Key as Byte
Dim Col as Byte
Dim Row as Byte
ALL_DIGITAL = True
LCD_DTPIN = PORTB.4
LCD_RSPIN = PORTB.2
LCD_ENPIN = PORTB.3
LCD_INTERFACE = 4 ' Setup the LCD
LCD_LINES = 2
LCD_TYPE = 0
Delayms 150 ' Allow LCD to warmup,
Cls
Delayms 10
Print At 1, 1, "Press any key..."
Main:
Gosub Wait_For_Key ' Loop until a key is pressed
If Key = 11 Then ' If 0 was pressed, change the value of key
Key = 0 '
EndIf '
If Key = 10 Then ' Display the data on the LCD, note:
Print At 2, 1, "*" ' 10 = "*" and 12 = "#"
ElseIf Key = 12 Then
Print At 2, 1, "#" '
Else '
Print At 2, 1, Dec Key '
EndIf '
Gosub Keypad_Debounce ' Wait for the user to depress the key
Goto Main ' Loop forever
Wait_For_Key: ' Loop until any key is pressed
Gosub Keypad_Decode
If Key = 0 Then Goto Wait_For_Key ' If 0 was returned, then loop
Return ' Input has been captured, return
Keypad_Decode:
Key = 0 ' Reset the key value
KeypadTris = %00001111 ' Make 7-4 outputs and 3-0 inputs
For Col = 4 to 6 ' 4 columns in keypad
SetBit KeypadPort, Col ' Set one Col high,
Row = KeypadPort & $0F ' and check if a row is high
ClearBit KeypadPort, Col ' Set the Col low
If Row <> 0 Then Goto Gotkey ' If a Row was high, then grab the key
Next
Return ' No keys down, then return
Gotkey:
Key = ((NCD Row - 1) * 3) + (Col - 3) 'Calculate what button was pressed
' Row = 1 to 4 and Col = 1 to 3
' So to calculate the key, determine what row equals
' by using NCD (Returns a decimal value of the MSB in
' the variable, eg, %00001000 would return the value 4
' and 00000010 would return 2. Then minus 1 from Row,
' so that it is a value between 0 and 3, and as Col
' is assigned to the upper part of the port, minus 3
' from it so it equals 1 to 3.
' Now if Row = 0 and Col = 1 then key pressed = 1 (Row + Col)
Return 'Subroutine over
Keypad_Debounce: ' This routine will only exit if
' all keys are depressed
Delayms 10 ' Debounce time
' Wait for all keys up
KeypadTris = %00001111
KeypadPort = %11110000
If (KeypadPort << 4) <> $00 Then Goto Keypad_Debounce
Return