Instructables

How To Connect a PS/2 Keyboard to the iPhone

Step 9: The Arduino Code

Picture of The Arduino Code

The Arduino software clocks data out of the keyboard, translates the keyboard scan codes to key codes, and handles presses of the shift and caps lock keys.

First off, download and install the Arduino development environment from here.  Follow the directions on the site, but be sure to install the appropriate FTDI driver from the drivers directory in the Arduino installation.

Next, you’ll need an additional Arduino library for PS/2.  Download the file “ps2.zip” from this page.  To install, unzip the download to a folder and move that folder to be a subdirectory of the “hardware/libraries” directory under your Arduino installation.  On OSX, you can go to Arduino.app and “Show Package Contents” first.

Once Arduino and the ps2 library are installed, download the source code from here.  Open the Arduino application, create a new project, and paste the source code into it.  Save, and then go to Sketch->Verify/Compile to make sure that it builds.  If it doesn’t, make sure the library is installed correctly.

On a side note, I actually wrote absolutely no code for this project.  I started out trying to use the PS2KeyboardExt2 library, but that library is based on interrupts and while it can run on an Arduino that is also speaking serial at 9600 bps, once I cranked the serial up to 19200 bps, the interrupts stopped working in a stable way.  So I yanked all of the nice code out of PS2KeyboardExt2, including the key definitions and the nice handling of shifts and caps lock and reworked it into a program that doesn’t use interrupts and makes use of a different, much simpler PS/2 library.  This makes it capable of handling 19200 bps serial in a reliable manner.

Now, to program the Arduino!

Disconnect the lead going to Pin 1 on the Arduino.  Then, connect the Arduino to your computer via USB cable.  You may need to restart the Arduino application so that it detects the new USB serial device correctly.  Load the saved sketch with the source, and then hit the Upload button to program the Arduino.

Once the program is uploaded, plug the keyboard into the PS/2 connector.  You should see the lights flash.  You can open up the Serial Monitor in the Arduino application and try typing some letters on the keyboard.  You should see those letters show up in the Serial Monitor.  Try turning the Caps Lock on and off, the light on the keyboard should go on and off and the characters should come out correctly capitalized.