Install joystick using the command below:
sudo apt-get install joystick
after installation you can find file js0 in the directory:
/dev/input/
sudo cat /dev/input/js0
sudo cat /dev/input/js0 | hexdump
Pygame program to read joystick buttons
joystick = pg.joystick.Joystick(0) joystick.init()
pg.joystick.joystick(0) returns the joystick object and init() function initialize the device values.
button1 = joystick.get_button(0) retrives the button(0)
below program includes functions to read the keyboard input and mouse inputs.
Pygame Joystick program:
import pygame as pg # initialize pygame pg.init() # use an image you have (.bmp .jpg .png .gif) image_file = "ball" # RGB color tuple for screen background black = (0,0,0) # screen width and height sw = 640 sh = 480 # create a screen screen = pg.display.set_mode((sw, sh)) # give the screen a title pg.display.set_caption('image follows mouse click position') # load an image # convert() unifies the pixel format for faster blit image = pg.image.load(image_file).convert() # get the rectangle the image occupies # rec(x, y, w, h) start_rect = image.get_rect() image_rect = start_rect running = True joystick = pg.joystick.Joystick(0) joystick.init() while running: event = pg.event.poll() keyinput = pg.key.get_pressed() button3 = joystick.get_button(2) button1 = joystick.get_button(0) # exit on corner 'x' click or escape key press if keyinput[pg.K_ESCAPE]: raise SystemExit elif event.type == pg.QUIT: running = False elif keyinput[pg.K_LEFT]: image_rect.left = image_rect.left - 1 image_rect.right = image_rect.right-1 print "corner coordinates --> (%d, %d, %d, %d)" % \ (image_rect.left, image_rect.top, image_rect.right, image_rect.bottom) screen.fill(black) elif keyinput[pg.K_RIGHT]: image_rect.left = image_rect.left + 1 image_rect.right = image_rect.right+1 screen.fill(black) screen.blit(image, image_rect) pg.display.flip() elif keyinput[pg.K_DOWN]: image_rect.top = image_rect.top + 1 image_rect.bottom = image_rect.bottom+1 screen.fill(black) screen.blit(image, image_rect) pg.display.flip() elif keyinput[pg.K_UP]: image_rect.top = image_rect.top - 1 image_rect.bottom = image_rect.bottom-1 screen.fill(black) screen.blit(image, image_rect) pg.display.flip() elif button3: print("Joystick up pressed") image_rect.top = image_rect.top - 1 image_rect.bottom = image_rect.bottom-1 screen.fill(black) screen.blit(image, image_rect) pg.display.flip() elif button1: print("Joystick down pressed") image_rect.top = image_rect.top + 1 image_rect.bottom = image_rect.bottom+1 screen.fill(black) screen.blit(image, image_rect) pg.display.flip()
Pygame built with Raspberry Pi & Joystick