Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify which button is being pressed on PS4 controller using pygame

I am using a Raspberry Pi 3 to control a robotic vehicle. I have successfully linked my PS4 controller to the RPi using ds4drv. I have the following code working and outputting "Button Pressed"/"Button Released" when a button is pressed/released on the PS4 controller using pygame. I am wondering how to identify which button is exactly being pressed.

ps4_controller.py

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                print("Button Pressed")
            elif event.type == pygame.JOYBUTTONUP:
                print("Button Released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
like image 975
Ctpelnar1988 Avatar asked Oct 04 '17 05:10

Ctpelnar1988


1 Answers

Figured out a hack.

The PS4 buttons are numbered as the following:

0 = SQUARE

1 = X

2 = CIRCLE

3 = TRIANGLE

4 = L1

5 = R1

6 = L2

7 = R2

8 = SHARE

9 = OPTIONS

10 = LEFT ANALOG PRESS

11 = RIGHT ANALOG PRESS

12 = PS4 ON BUTTON

13 = TOUCHPAD PRESS

To figure out which button is being pressed I used j.get_button(int), passing in the matching button integer.

Example:

import pygame

pygame.init()

j = pygame.joystick.Joystick(0)
j.init()

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                print("Button Pressed")
                if j.get_button(6):
                    # Control Left Motor using L2
                elif j.get_button(7):
                    # Control Right Motor using R2
            elif event.type == pygame.JOYBUTTONUP:
                print("Button Released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
like image 56
Ctpelnar1988 Avatar answered Sep 20 '22 19:09

Ctpelnar1988