python - 如何使用pygame识别PS4 Controller 上按下的是哪个按钮

标签 python raspberry-pi pygame

我正在使用 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/

相关文章:

python - 它们是 "same"吗? (代码 war )

python - 哪个更可取使用 : lambda functions or nested functions ('def' )?

python - 使用 ABC 和 ABCMeta 有什么区别吗?

python - Python Speech_recognition无法检测到麦克风的音频

python - pydispatch 模块已安装但仍然找不到

java - 有关于 Raspberry PI 的 Java 经验吗?

python - 从 azure 函数访问 keyvault secret 失败

python - 在pygame中切换菜单

python - Pygame 文本优化

Python - 如何加快pygame的流畅度?