Ctp*_*988 4 python pygame raspberry-pi
我正在使用Raspberry Pi 3来控制机器人车辆。我已成功使用将我的PS4控制器链接到RPi ds4drv。当使用PS4控制器上的一个按钮被按下/释放时,我有以下代码工作并输出“ Button Pressed” /“ Button Released” pygame。我想知道如何确定哪个按钮被完全按下。
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()
Run Code Online (Sandbox Code Playgroud)
你真的很亲近!通过一些调整,你的代码变成了这样:
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.JOYAXISMOTION:
print(event.dict, event.joy, event.axis, event.value)
elif event.type == pygame.JOYBALLMOTION:
print(event.dict, event.joy, event.ball, event.rel)
elif event.type == pygame.JOYBUTTONDOWN:
print(event.dict, event.joy, event.button, 'pressed')
elif event.type == pygame.JOYBUTTONUP:
print(event.dict, event.joy, event.button, 'released')
elif event.type == pygame.JOYHATMOTION:
print(event.dict, event.joy, event.hat, event.value)
except KeyboardInterrupt:
print("EXITING NOW")
j.quit()
Run Code Online (Sandbox Code Playgroud)
我发现在编写 up 时有帮助的一些资源包括pygame 的事件文档,使用 python 的dir函数查看 python 对象具有哪些属性,以及pygame 的父 C 库的文档,如果您想更深入地解释属性实际上是什么,SDL方法。我包括字典访问版本(使用event.dict)以及属性访问版本(仅使用event.whatever_the_property_name_is)。请注意,event.button只给您一个数字;由您手动创建每个按钮编号在控制器上的含义的映射。希望这能解决问题!
找出了一个hack:
PS4按钮编号如下:
0 = SQUARE
1 = X
2 = CIRCLE
3 = TRIANGLE
4 = L1
5 = R1
6 = L2
7 = R2
8 = SHARE
9 = OPTIONS
10 = LEFT ANALOG PRESS
11 = RIGHT ANALOG PRESS
12 = PS4 ON BUTTON
13 = TOUCHPAD PRESS
为了弄清楚哪个按钮被按下,我使用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()
Run Code Online (Sandbox Code Playgroud)