Skip to content

Instantly share code, notes, and snippets.

@claymcleod
Last active December 15, 2022 21:40
Show Gist options
  • Star 47 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save claymcleod/028386b860b75e4f5472 to your computer and use it in GitHub Desktop.
Save claymcleod/028386b860b75e4f5472 to your computer and use it in GitHub Desktop.
Playstation 4 Controller Python
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file presents an interface for interacting with the Playstation 4 Controller
# in Python. Simply plug your PS4 controller into your computer using USB and run this
# script!
#
# NOTE: I assume in this script that the only joystick plugged in is the PS4 controller.
# if this is not the case, you will need to change the class accordingly.
#
# Copyright © 2015 Clay L. McLeod <clay.l.mcleod@gmail.com>
#
# Distributed under terms of the MIT license.
import os
import pprint
import pygame
class PS4Controller(object):
"""Class representing the PS4 controller. Pretty straightforward functionality."""
controller = None
axis_data = None
button_data = None
hat_data = None
def init(self):
"""Initialize the joystick components"""
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
def listen(self):
"""Listen for events to happen"""
if not self.axis_data:
self.axis_data = {}
if not self.button_data:
self.button_data = {}
for i in range(self.controller.get_numbuttons()):
self.button_data[i] = False
if not self.hat_data:
self.hat_data = {}
for i in range(self.controller.get_numhats()):
self.hat_data[i] = (0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
self.axis_data[event.axis] = round(event.value,2)
elif event.type == pygame.JOYBUTTONDOWN:
self.button_data[event.button] = True
elif event.type == pygame.JOYBUTTONUP:
self.button_data[event.button] = False
elif event.type == pygame.JOYHATMOTION:
self.hat_data[event.hat] = event.value
# Insert your code on what you would like to happen for each event here!
# In the current setup, I have the state simply printing out to the screen.
os.system('clear')
pprint.pprint(self.button_data)
pprint.pprint(self.axis_data)
pprint.pprint(self.hat_data)
if __name__ == "__main__":
ps4 = PS4Controller()
ps4.init()
ps4.listen()
@JaviOrtega88
Copy link

I have my controller connected to my ps4 via Bluetooth and USB to my pc. Is there a way to simulate an action from my pc?

@danieldram
Copy link

That would be awesome if we could figure this out

@PaolomaldiniI
Copy link

how can i control the leds controller with python ?

@concealedfox70
Copy link

how do i select a specific button axis or hat value to use it for my script? below is what you wrote, but it explains absolutely nothing other than how to print which nobody really wants to do
# Insert your code on what you would like to happen for each event here!
# In the current setup, I have the state simply printing out to the screen.

@Theringer1976
Copy link

Theringer1976 commented Aug 11, 2018

Try this edited while loop: Here you should be able to tell specifically where your code should go.

        while True:
            for event in pygame.event.get():
                if event.type == pygame.JOYAXISMOTION:
                    if event.axis == 0:
                        if event.value > 0:
                            print "right"
                        if event.value < 0:
                            print "left"
                    if event.axis == 1:
                        if event.value > 0:
                            print "down"
                        if event.value < 0:
                            print "up"
                elif event.type == pygame.JOYBUTTONDOWN:
                    if event.button == 1:
                        print "wow pressed the X button"
                elif event.type == pygame.JOYBUTTONUP:
                    if event.button == 1:
                        print "he-yump"
                elif event.type == pygame.JOYHATMOTION:
                    if event.hat == 0:
                        if event.value == (1, 0):
                            print "right"
                        if event.value == (-1, 0):
                            print "left"
                        if event.value == (0, 1):
                            print "up"
                        if event.value == (0, -1):
                            print "down"

                # Insert your code on what you would like to happen for each event here!
                # In the current setup, I have the state simply printing out to the screen.

                #os.system('clear')
                #pprint.pprint(self.button_data)
                #pprint.pprint(self.axis_data)
                #pprint.pprint(self.hat_data)

You can use his app to figure out the number associated with the button, but this should get you started. Joysticks are SENSITIVE :)

@ArturSpirin
Copy link

There is a ready available solution now, I wrote a package that does not require pygame or any other packages and binding to button events is as easy as:

from pyPS4Controller.controller import Controller
    
    
class MyController(Controller):

    def __init__(self, **kwargs):
        Controller.__init__(self, **kwargs)

    def on_x_press(self):
       print("Hello world")

    def on_x_release(self):
       print("Goodbye world")

controller = MyController(interface="/dev/input/js0", connecting_using_ds4drv=False)
# you can start listening before controller is paired, as long as you pair it within the timeout window
controller.listen(timeout=60)

Package is available on GitHub & PyPi

@eighta
Copy link

eighta commented Feb 28, 2020

how can i control the leds controller with python ?
changing the value (0 - 255) on this file:
'/sys/class/leds/' + dsId + ':' + led + '/brightness'

@thiagosm1
Copy link

Hello, im brazilian and i want to make a software with a new function to the ds4 controller, but i need to know, I can make a telemetry system like SIM Dashboard with Python?

@justinpaulturner
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment