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

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()

You are really close! With a few tweaks, you code becomes this instead:

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.JOYAXISMOTION:
                print(event.dict, event.joy, event.axis, event.value)
            elif event.type == pygame.JOYBALLMOTION:
                print(event.dict, event.joy, event.ball, event.rel)
            elif event.type == pygame.JOYBUTTONDOWN:
                print(event.dict, event.joy, event.button, 'pressed')
            elif event.type == pygame.JOYBUTTONUP:
                print(event.dict, event.joy, event.button, 'released')
            elif event.type == pygame.JOYHATMOTION:
                print(event.dict, event.joy, event.hat, event.value)

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

Some resources that I found helpful in writing the up included pygame's event documentation, the use of python's dir function to see what properties a python object has, and the documentation for pygame's parent C library, SDL if you wanted a deeper explanation of what the property actually means. I included both the dictionary access version (using event.dict) as well as the property-access version (using just event.whatever_the_property_name_is). Note that event.button only gives you a number; it is up to you to manually create a mapping of what each button number means on your controller. Hope this clears it up!