我正在使用 Raspberry Pi 3 来控制机器人车辆。我已经使用 ds4drv
成功地将我的 PS4 Controller 链接到 RPi。当使用 pygame
在 PS4 Controller 上按下/释放按钮时,我有以下代码在工作并输出“Button Pressed”/“Button Released”。我想知道如何确定确切按下了哪个按钮。
ps4_controller.py
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
print("Button Pressed")
elif event.type == pygame.JOYBUTTONUP:
print("Button Released")
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
最佳答案
想出了一个 hack。
PS4 按钮编号如下:
0 = 方形
1 = X
2 = 圆
3 = 三角形
4 = L1
5 = R1
6 = L2
7 = R2
8 = 分享
9 = 选项
10 = 左模拟按键
11 = 右模拟按键
12 = PS4 开启按钮
13 = 触控板按下
为了确定哪个按钮被按下,我使用了 j.get_button(int)
,传入匹配的按钮整数。
例子:
import pygame
pygame.init()
j = pygame.joystick.Joystick(0)
j.init()
try:
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.JOYBUTTONDOWN:
print("Button Pressed")
if j.get_button(6):
# Control Left Motor using L2
elif j.get_button(7):
# Control Right Motor using R2
elif event.type == pygame.JOYBUTTONUP:
print("Button Released")
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
关于python - 如何使用pygame识别PS4 Controller 上按下的是哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46557583/