Posts: 7
Joined: Sat May 04, 2013 10:27 pm

Reading joysticks inputs

Mon May 13, 2013 12:31 am

Hello, I am working on a project where I read a USB joystick's inputs and convert it to a PPM stream. It technically isn't gaming but I figured this would be my best bet at getting an answer since it deals with reading the USB inputs from a gaming device.

My project is very similar to this arduino project:,8755.0.html

Pretty much, I want to use a joystick to fly my planes AND learn about Raspberry Pi. With an arduino, I would just read the buttons and potentiometers and convert it to PPM but I want to interface with USB.

So, is there any add-ons to python that would let me read the inputs? I think that is my biggest hurdle right now. I was going to use the Rpi's audio jack to output the signal, but that is a battle for another day (and sub forum).


Posts: 3800
Joined: Fri Jun 08, 2012 6:03 pm

Re: Reading joysticks inputs

Mon May 13, 2013 9:46 pm

Pygame should allow you to access the joystick.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
Posts: 2462
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Reading joysticks inputs

Tue May 14, 2013 7:48 am

Or if you use pi3d you can plug pretty much anything into the USB and read it with the Events module the demo uses this
I'm sure there's python libraries to send your output to the GPIO pins

Posts: 7
Joined: Sat May 04, 2013 10:27 pm

Re: Reading joysticks inputs

Wed May 15, 2013 6:45 pm

I was able to get the RPI to run the example code off the pygame website and it works well. The only thing is, it makes the RPI run at 100% CPU and +5c degrees hotter. I tried to install PI3D but I am having troubles unzipping it.

Now I just gotta figure out how to use the audio port to put out a PPM signal.

Just a note on the pygame example code, for anyone who finds this thread later on. The script calls for a class called def print. It won't run- you have to capitalize the P in print for all related functions. So it becomes def Print and textPrint.Print. I reposted it just in case if anyone is interested.

Code: Select all

import pygame

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)

# This is a simple class that will help us print to the screen
# It has nothing to do with the joysticks, just outputing the
# information.
class TextPrint:
    def __init__(self):
        self.font = pygame.font.Font(None, 20)

    def Print(self, screen, textString):
        textBitmap = self.font.render(textString, True, BLACK)
        screen.blit(textBitmap, [self.x, self.y])
        self.y += self.line_height
    def reset(self):
        self.x = 10
        self.y = 10
        self.line_height = 15
    def indent(self):
        self.x += 10
    def unindent(self):
        self.x -= 10

# Set the width and height of the screen [width,height]
size = [500, 700]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("My Game")

#Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Initialize the joysticks
# Get ready to print
textPrint = TextPrint()

# -------- Main Program Loop -----------
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
        if event.type == pygame.JOYBUTTONDOWN:
            print("Joystick button pressed.")
        if event.type == pygame.JOYBUTTONUP:
            print("Joystick button released.")
    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.

    # Get count of joysticks
    joystick_count = pygame.joystick.get_count()

    textPrint.Print(screen, "Number of joysticks: {}".format(joystick_count) )
    # For each joystick:
    for i in range(joystick_count):
        joystick = pygame.joystick.Joystick(i)
        textPrint.Print(screen, "Joystick {}".format(i) )
        # Get the name from the OS for the controller/joystick
        name = joystick.get_name()
        textPrint.Print(screen, "Joystick name: {}".format(name) )
        # Usually axis run in pairs, up/down for one, and left/right for
        # the other.
        axes = joystick.get_numaxes()
        textPrint.Print(screen, "Number of axes: {}".format(axes) )
        for i in range( axes ):
            axis = joystick.get_axis( i )
            textPrint.Print(screen, "Axis {} value: {:>6.3f}".format(i, axis) )
        buttons = joystick.get_numbuttons()
        textPrint.Print(screen, "Number of buttons: {}".format(buttons) )

        for i in range( buttons ):
            button = joystick.get_button( i )
            textPrint.Print(screen, "Button {:>2} value: {}".format(i,button) )
        # Hat switch. All or nothing for direction, not like joysticks.
        # Value comes back in an array.
        hats = joystick.get_numhats()
        textPrint.Print(screen, "Number of hats: {}".format(hats) )

        for i in range( hats ):
            hat = joystick.get_hat( i )
            textPrint.Print(screen, "Hat {} value: {}".format(i, str(hat)) )

    # Go ahead and update the screen with what we've drawn.

    # Limit to 20 frames per second
# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit ()

Posts: 3
Joined: Tue May 21, 2013 9:53 pm
Location: Poland
Contact: Website

Re: Reading joysticks inputs

Tue May 21, 2013 10:05 pm

Hi, I have similiar project but for two wheel-er robot. If you are still interested, I've made some post about reverse engineering of usb joystick communication protocol. I'm going to write python code for this in next month... just for fun :) ... -protocol/
software, robotics, engineering & geeky stuff…

User avatar
Posts: 2462
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Reading joysticks inputs

Wed May 22, 2013 8:36 am

joecarb, as you're just putting a few bits of text on screen you might be able to reduce the graphics load by just changing the rectangles you need rather than re-painting the whole screen. Using the gpu (as in pi3d) this doesn't make much difference as it's so quick but for pygame it might help.

Also I would like to know what your unzipping troubles where and if you got pi3d running. It may be a bit over the top to have all the 3d graphics to hand but rurwin's events module (mouse, keyboard, joystick etc) is very capable.

Return to “Gaming”