Binary Strolls

Cyber rambling (or ranting), mostly about code

Arrow Keys input in python.

January 9, 2012 , posted in programing, python

I had an assignment to write an applicaion to control a toy helicopter. It should accept the inputs from the arrow keys and then generate a serial signal. The serial port is connected to the interfacing circutary.

The major problem I faced was how to take arrow keys as input? Using the technical jargon - implement a non-bufferd input. A code to do it in console can be found here. But its dirty and is implemented in a complex way that usage is little bit diffcult. At console level the code becomes more os-specific, as you can see from the above code. It has diffrent defenitions to implement the feature in each os.

The easy way to do this is using any windowing tool kits around, they all have a key logging abstraction implemented. Like this code. it uses the tkinter toolkit to read input. The way I suggest is using pygame, because it is designed to this stuff. (Which game doesnt have a single use arrow key used?)

You can get the keys from

{% codeblock lang:python %} pressed_keys = pygame.key.get_pressed() {% endcodeblock %} and the key name as

{% codeblock lang:python %} for key_constant in pressed_keys:
key_name = pygame.key.name(key_constant) {% endcodeblock %}

Then its just a matter of comparing them with the key name,( of arrow keys in our case).

{% codeblock lang:python %} if key_constant == ‘up’: port.write(_up_data) {% endcodeblock %}

The complete code is available in github