Python:同时读取和命令不同设备的最佳方式是什么?

2024-04-27 23:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我用树莓皮和砖块来控制乐高汽车。我想从一个游戏板,如罗技F310输入,并运行基于操纵杆输入的电机。我发现从游戏板获取输入需要阻塞,比如for event in get_gamepad():,它会不断检查输入,除非得到输入,否则不会继续。另外,我的马达需要命令BrickPiUpdateValues()每分钟都能运行。所以我需要同时做两件事,但是游戏板阻止了马达更新。在

在这个对我有用的简短程序中,我使用了线程,但是有没有更好的方法来完成这项任务,或者更好地编写代码?而且,即使我试图使用tryexcept来允许键盘中断,Ctrl-C也不会退出gamepad线程。退出线程的好方法是什么?join没有很好地工作,因为它等待线程完成。在

from inputs import get_gamepad
from BrickPi import *
import threading

BrickPiSetup()
BrickPi.MotorEnable[PORT_A] = 1 #enable motor A

quitting = False #make the variable

def gamepad(): #the thread to read the gamepad
    while True:
        for event in get_gamepad(): #waits for input
            if event.code == "ABS_Y":
                BrickPi.MotorSpeed[PORT_A] = event.state / 128 #use joystick input to decide speed
            elif event.code == "BTN_MODE": #quit thread, program will quit as well
                global quitting
                quitting = True
                return

gamepad = threading.Thread(target = gamepad)
gamepad.start() #start reading the gamepad

while True:
    BrickPiUpdateValues() #actually run the motor
    if quitting == True: #full quit, triggered by mode button
        sys.exit()

Tags: the方法inimporteventtrue游戏for