domenica 16 febbraio 2014

Manage a 1 euro joystick with pygame

Today I wanted to make some tests with my new 1 euro joystick. After a quick search on Google I found that the python library pygame allows for direct polling of joysticks. The counterpart for Java is the Jinput library.
  1. Install python2-pygame
  2. Copy the following code to test your joysticks

Joystick Management
- Author: Andrea Monacchi
- Date: 2014, February 16th
from pygame import *

class JoystickMan:
    def __init__(self):
        self.joysticks = []

    def get_joystic_count(self):
        return joystick.get_count()

    def connect_joystick(self, id):
        joy = joystick.Joystick(id)
        if joy.get_init() == 1:
            print "Joystick is initialized"

    def connect_all_joysticks(self):
        for i in range(self.get_joystic_count()):
            joy = joystick.Joystick(i)

    def print_info(self):
        for i, joy in enumerate(self.joysticks):
            print "Joystick #", i," ID: ",joy.get_id(),", Name: ",joy.get_name()
            print "#Axes: ", joy.get_numaxes()
            print "#Trackballs: ", joy.get_numballs()
            print "#Buttons: ", joy.get_numbuttons()
            print "#Hat controls: ", joy.get_numhats()

    def terminate(self):
        quit() # quits pygame

    def run(self):
        while 1:
            for e in event.get():
                # Event list at:
                if e.type is JOYBUTTONDOWN:
                    name = 'joystick%d-button%d' % (, e.button)
                    print name
                elif e.type is JOYBUTTONUP:
                    name = 'joystick%d-button%d-up' % (, e.button)
                    print name
                elif e.type is JOYAXISMOTION:
                    name = 'joystick%d-axis%d' % (, e.axis)
                    print name, e.value
                elif e.type is JOYBALLMOTION:
                    name = 'joystick%d-ball%d' % (, e.hat)
                    print name, e.rel
                elif e.type is JOYHATMOTION:
                    name = 'joystick%d-hat%d' % (, e.hat)
                    print name, e.value

if __name__ == "__main__":
        j = JoystickMan()
    except KeyboardInterrupt:
        print "terminating"

Nessun commento:

Posta un commento