Happy Thanksgiving! While my wife was cooking Thanksgiving dinner (more like lunch for us...), I finally got around to messing around with a Logitech Dual Action gamepad I've had laying around. It's basically a PlayStation 2 controller with a USB connection on the end. It's got two joysticks, a D-pad, four right thumb buttons, 4 top controller buttons and two buttons in the middle of the controller.
After doing a modprobe joydev, I used a utility called jstest to test the joystick device. Then, it came time to start messing with the device. So out came python, and I found that pygame already had support for reading from a joystick. I had toyed with pygame before, but had never done anything specific. I wanted to see exactly how to read and react to the joystick events. Since I'd never really worked with joysticks before, I wrote a python script that only reads the joystick events and print the events (with a little bit of manipulation to make it human readable).
#!/usr/bin/env python
import pygame
#from pygame import joystick, event
pygame.init()
#joystick.init()
j = pygame.joystick.Joystick(0)
j.init()
print 'Initialized Joystick : %s' % j.get_name()
try:
while True:
pygame.event.pump()
for i in range(0, j.get_numaxes()):
if j.get_axis(i) != 0.00:
print 'Axis %i reads %.2f' % (i, j.get_axis(i))
for i in range(0, j.get_numbuttons()):
if j.get_button(i) != 0:
print 'Button %i reads %i' % (i, j.get_button(i))
except KeyboardInterrupt:
j.quit()
A few caveats I would like to mention that I ran into as I was writing this script. First, I tried to import pygame.joystick only. This allowed me to initialize the joystick, but it wasn't reading events. After reading some documentation, I found that pygame's joystick interface requires pygame.event.pump() to read events. However, only importing pygame.event and pygame.joystick still doesn't work, because event requires the pygame.video interface to be intialized. It lead me to see that pygame really must be imported altogether, and making one single call to pygame.init() allows interfacing with everything.
The entire reason I started this was to interface with an Arduino and control a robotic arm. This will involve pyserial, so I'll be posting more detailed code snippets later that will bring both python libraries together (and hopefully implement a good example of good coding patterns... :)
Leave a Comment