Making a simple gaming controller

View post on imgur.com

With the PiShield, we can easily turn sensors into input on the Raspberry Pi using the PyUserInput library. Here’s a short tutorial on the process! The above shows a 2 channel analog joystick used as direction keys in Minecraft. Read on to find out how to make your own…

Ingredients:

  • 1x Raspberry Pi board with keyboard, mouse and monitor, connected to the internet (if you have our pre-configured image, no internet connection is required as all the libraries are pre-installed).
  • 1x PiShield addon board
  • 1x I-CubeX Push2D Sensor, or similar directional sensor that outputs 2 analog channels with the same pinouts as defined here. You could even use two separate sensors, but it might be a bit hard to control! 🙂

If you’re using our pre-configured development image, skip the next section and go straight to the “Keyboard Emulation Code” section below!

Install Python libraries

In a terminal, clone the PyUserInput library and then install it with the following:

git clone https://github.com/SavinaRoja/PyUserInput
cd PyUserInput
sudo python setup.py install

Keyboard Emulation Code

Building upon the Turtle Example, we add the following:

near the top of the script, after the imports:
from pykeyboard import PyKeyboard
Initialize a keyboard object:
kbd = PyKeyboard()

Then, where we moved the turtle, we do the following instead:
if adcValues[1] < 200:
   print "UP!"
   kbd.press_key('w')
else:
   kbd.release_key('w')

… for each direction. Note we will need to emit the release of the key as well, otherwise it will be held for ever! The complete script is available in the Python examples repo, here.

In this example, we simply map the directions to the w, s, a, d keys, commonly used by many games. You could explore using a second controller to control the mouse in a similar manner. Have fun coding!

1 thought on “Making a simple gaming controller

  1. Pingback: Head nod controlled page turner for PDF scores – Infusion Systems

Leave a Reply