I recently wrote a Swordfish module which simplifies the process of interfacing with a PS2 Keyboard.
Here's an example of the module in use. Note that its as simple as calling the function "swKBD.NewKey". From there, if a key has been pressed, it is extracted and stored in the registers KBD.KeyChar and KBD.KeyCode (KeyChar contains the converted ASCII character while KeyCode contains the raw scan key code):
Device = 18F2520 // 18F2520 PIC in use, could be any 18F PIC Clock = 32 // clock speed is 32Mhz (8MIPS) Config MCLRE = Off // disable MCLR Include "InternalOscillator.bas" // search for "User Module Pack" at www.digital-diy.com Include "USART.bas" // used for displaying content on a uart terminal Include "swKBD.bas" // PS2 Keyboard module. URL http://digital-diy.com/home/swordfish/user-modules/242-ps2-keyboard-module-swkbdbas.html SetBaudrate(br38400) // initialise USART for 38400 baud USART.Write("Power On",13,10) // send a message to the terminal While True // main program loop If swKBD.NewKey Then // checks the device for new information If KBD.ValidChar Then // ensure the key is a valid non-white space character USART.Write(KBD.KeyChar) // yes, display it via USART ElseIf KBD.KeyCode = KBD_ENTER Then // check if the 'Enter' key was pressed USART.Write(13,10) // yes, send a line feed and carriage return EndIf // EndIf // High(PORTB.7) // toggle PORTB.7 high then low, Low(PORTB.7) // to measure the time it takes between loops Wend //
A handy feature that was recently added detects if the keyboard has been unplugged, and will automatically re-configure the keyboard when it is reconnected.
Thanks to the PORTB pull-up trick, you get upwards of 101 keys at the cost of 4 wires like so:
You can find the latest version of the module in the article: PS/2 Keyboard Module (swKBD.bas) (along with detailed usage/tips)