Created
May 20, 2024 05:30
-
-
Save EncodeTheCode/f2fe16860b8e4a0e3e7c704f29d2461e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install hidapi | |
import hid | |
import time | |
# Define the vendor ID and product ID for the PlayStation 1 controller | |
VENDOR_ID = 0x054C | |
PRODUCT_ID = 0x05C4 | |
# Define the bit masks for each button | |
BUTTONS = { | |
'TRIANGLE': 0x1000, | |
'CIRCLE': 0x2000, | |
'CROSS': 0x4000, | |
'SQUARE': 0x8000 | |
} | |
def is_button_pressed(data, button): | |
# Combine the two bytes of button state (data[5] and data[6]) into a 16-bit word | |
button_state = (data[5] << 8) | data[6] | |
return (button_state & button) == 0 | |
def main(): | |
# Initialize the HID library | |
hid.api.init() | |
# Open the PlayStation 1 controller device | |
controller = hid.api.open(VENDOR_ID, PRODUCT_ID) | |
if not controller: | |
print("Failed to open PlayStation 1 controller device") | |
return | |
print("PlayStation 1 controller connected!") | |
try: | |
while True: | |
# Read data from the controller (64 bytes) | |
data = controller.read(64) | |
if data: | |
# Print the state of each button | |
print("Triangle pressed:", is_button_pressed(data, BUTTONS['TRIANGLE'])) | |
print("Circle pressed:", is_button_pressed(data, BUTTONS['CIRCLE'])) | |
print("Cross pressed:", is_button_pressed(data, BUTTONS['CROSS'])) | |
print("Square pressed:", is_button_pressed(data, BUTTONS['SQUARE'])) | |
# Delay to prevent spamming the output | |
time.sleep(0.1) | |
except KeyboardInterrupt: | |
print("Exiting...") | |
finally: | |
# Close the controller device and exit | |
controller.close() | |
hid.api.exit() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment