Created
April 1, 2023 03:36
-
-
Save TheyCallMeLinux/f73c11f7d4d1e22e91ef44a1e65df392 to your computer and use it in GitHub Desktop.
Python code for PCA9685 Servo Controller and Joystick Control
This file contains hidden or 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
#!/usr/bin/env python | |
import time | |
import Adafruit_PCA9685 | |
import evdev | |
# Initialise the PCA9685 using the default address (0x40). | |
pwm = Adafruit_PCA9685.PCA9685() | |
# Set frequency to 60hz, good for servos. | |
pwm.set_pwm_freq(60) | |
# Find the gamepad | |
devices = [evdev.InputDevice(path) for path in evdev.list_devices()] | |
for device in devices: | |
if device.name == 'Logitech Logitech Attack 3': | |
gamepad = evdev.InputDevice(device.path) | |
# Servo channel numbers | |
SERVO_X_CHANNEL = 0 | |
SERVO_Y_CHANNEL = 1 | |
# Servo minimum and maximum pulse lengths | |
SERVO_MIN_PULSE_LEN = 150 # Min pulse length out of 4096 | |
SERVO_MAX_PULSE_LEN = 600 # Max pulse length out of 4096 | |
# X and Y axis current positions | |
x_pos = 0 | |
y_pos = 0 | |
# Loop through events from the gamepad | |
for event in gamepad.read_loop(): | |
# Break out of the loop if program has been terminated | |
if event.type == evdev.ecodes.EV_KEY and event.code == 316 and event.value == 0: | |
break | |
# Read joystick event and update position if it's X or Y axis | |
if event.type == evdev.ecodes.EV_ABS: | |
if event.code == 0: | |
x_pos = event.value | |
elif event.code == 1: | |
y_pos = event.value | |
# Convert joystick position to servo pulse length | |
x_pulse_len = int((SERVO_MAX_PULSE_LEN - SERVO_MIN_PULSE_LEN) * (x_pos / 255.0) + SERVO_MIN_PULSE_LEN) | |
y_pulse_len = int((SERVO_MAX_PULSE_LEN - SERVO_MIN_PULSE_LEN) * (y_pos / 255.0) + SERVO_MIN_PULSE_LEN) | |
# Set the servo position | |
pwm.set_pwm(SERVO_X_CHANNEL, 0, x_pulse_len) | |
pwm.set_pwm(SERVO_Y_CHANNEL, 0, y_pulse_len) | |
# Print current X and Y values | |
print(f"X: {x_pos}, Y: {y_pos}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment