pythonpygameraspberry-pigamepad

Can I use pygame without 'video system', just for gamepad input?


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.


Solution

  • No, you can't. See pygame.event:

    Pygame handles all its event messaging through an event queue. The routines in this module help you manage that event queue. The input queue is heavily dependent on the pygame.display module to control the display window and screen module. If the display has not been initialized and a video mode not set, the event queue may not work properly.

    So you need a window and the video system for the event handling.