模拟控制 Raspberry pi 使用 pyPS4Controller

Analog control Raspberry pi using pyPS4Controller

我有一个带有机器人套件的​​ Raspberry Pi,我想使用 PS4 控制器但使用模拟输入来控制它。我已成功连接控制器,我可以读取事件并对电机进行编程以响应二进制输入。然而,documentation (pyPS4Controller) 并未明确使用 模拟 值(例如:50% 按下 R2 输出 0.5 向前)。

有人能帮我弄清楚怎么做吗?
提前致谢!

# This is the example for binary buttons

from pyPS4Controller.controller import Controller

class MyController(Controller):

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

    def on_x_press(self):
       print("Forward")

    def on_x_release(self):
       print("Stop")

# --> The objective is having some way to capture the "intensity" of the button press to use the motors accordingly

controller = MyController(interface="/dev/input/js0", connecting_using_ds4drv=False)
controller.listen()

经过一些调整和反复试验,我最终找到了解决方案。 模拟功能接收名为 value 的输入,其中包含提供给控制器的输入的模拟值。

from pyPS4Controller.controller import Controller
from gpiozero import CamJamKitRobot as camjam

# Translate controller input into motor output values
def transf(raw):
    temp = (raw+32767)/65534
    # Filter values that are too weak for the motors to move
    if abs(temp) < 0.25:
        return 0
    # Return a value between 0.3 and 1.0
    else:
        return round(temp, 1)

class MyController(Controller):

    def __init__(self, **kwargs):
        Controller.__init__(self, **kwargs)
        self.robot = camjam()
    
    def on_R2_press(self, value):
        # 'value' becomes 0 or a float between 0.3 and 1.0
        value = transf(value)
        self.robot.value = (value, value)
        print(f"R2 {value}")
    
    def on_R2_release(self):
        self.robot.value = (0,0)
        print(f"R2 FREE")
    
    def on_L2_press(self, value):
        # 'value' becomes 0 or a float between -1.0 and -0.3
        value = -transf(value)
        self.robot.value = (value, value)
        print(f"L2 {value}")
    
    def on_L2_release(self):
        self.robot.value = (0,0)
        print(f"L2 FREE")
    
    # Press OPTIONS (=START) to stop and exit
    def on_options_press(self):
        print("\nExiting (START)")
        self.robot.value = (0,0)
        exit(1)


controller = MyController(interface="/dev/input/js0", connecting_using_ds4drv=False)
controller.listen()