Skip to content

Instantly share code, notes, and snippets.

Last active December 15, 2022 21:40
Show Gist options
  • 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 <>
# 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"""
self.controller = pygame.joystick.Joystick(0)
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.
if __name__ == "__main__":
ps4 = PS4Controller()
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'

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?

Copy link

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