I'm trying to build a raspberry pi controlled robot. In particular, I want to use a gamepad to navigate the robot. I wrote the following code on my desktop computer to capture the gamepad input:
import pygame
pygame.init()
joystick = pygame.joystick.Joystick(0)
joystick.init()
done = False
while not done:
event = pygame.event.poll()
if event.type == 1538:
print(event.dict['value'])
if event.type == 1540:
done = True
This code prints the value (e.g. (1, 0) ) if a button on the navigation cross is pressed, and it terminates if another button is pressed.
When I run this code on the raspberry pi, I get the following error:
pygame.error: video system not initialized
I guess the problem is, that I run the code on the command line, while pygame expects a window for video output. But I don't want to have output, I just want to use pygame to read input. Is there a way to configure pygame to do just that?
UPDATE
It seems that pygame can't do what I was aiming for (see answer of rabbid76). During my search for an alternative, I found the module inputs. The following code does works on the raspberry pi zero and can be used to read inputs:
from inputs import get_gamepad
done = False
while not done:
events = get_gamepad()
for event in events:
print(event.code)
print(event.state)
print(event.ev_type)
I recommend you to run the code and review the output yourself. The output values were different on my desktop computer and on my raspberry pi zero, so you might have to find the right code for your specific situation.
No, you can't. See
pygame.event:So you need a window and the video system for the event handling.