Using USB Keyboard

Good progress!

If you are happy with just sending the code values, then you don't need the KeyLookup array. It's function is to translate that key code value (which could theoretically be up to 3 digits) into an ASCII character. It's these lines that do it:

           if code < len(KeyLookup):
                barcode = barcode +  KeyLookup[code]

This checks to see if the "code" variable has a value that is less than the number of rows in the lookup table. If it's out of range, the value is simply ignored and nothing is sent (the check prevents an error from trying to access an array with an index that is too big.) If it is in the range of the lookup table, it takes the code value and uses it as an index into the lookup table: if the code value is 0, it takes the first row, which is nothing; if 1 it takes the value in the second row which is also nothing; if 2 it takes the value in the third row which is the character '0', and so on up until a value of 53 takes the value in row 52 which is a slash character. (Arrays are zero based, so the index of the first row is zero, not one.)

You could use logic something like this:

    if type == 1 and value == 1:
        if code < len(KeyLookup):
            print KeyLookup[code]

This looks to see if the code is in the array. If not, it is thrown away. If it is in range, the corresponding code is translated to an ASCII character and printed.

There are some significant advantages to the translation:

  • It's got to be decoded at some point, and the Linux side has more speed and resources than the sketch to do it
  • It's less data to send over the relatively slow serial link (one character instead of one, two, or three)
  • Because it's a single character, as opposed to one through three digits, there is no chance of things getting out of sync - you don't have to worry about losing a character or getting an extra noise character and getting the wrong data. And you don't have to worry if a code is more or less than the two digits you are expecting

To get a better understanding of the key codes, the USB HID spec >LINK< lists the scan code in chapter 10, page 53. This is how you translate the code numbers to the key meanings (74=keypad home, 75=keypad PageUp, 14='K'.) It's interesting that you're getting 69s with numlock on, that's the code for F12. I would've expected you to get key codes saying the numlock key is pressed, and you need to keep track of the state.

If you are getting meaningful codes up in the 75 range, then you will need a much longer lookup table. But if you only have 18 keys, that's a lot of wasted slots in the table. Instead of an array, you might do well using a dictionary (look it up on your favorite Python reference source) to translate the code into a decoded character.[/code]
[/code]