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

时间:2017-06-24 18:45:05

标签: python multithreading

我使用带有BrickPi的Raspberry Pi来控制乐高电机。我想从游戏手柄中获取输入,比如罗技F310,并根据操纵杆输入运行电机。我发现从游戏手柄获取输入需要阻止,例如for event in get_gamepad():,它会不断检查输入,除非得到输入,否则不会继续。此外,我的电机每时每刻都需要命令BrickPiUpdateValues()才能运行。所以我需要同时做两件事,但游戏手柄会阻止电机更新。

在这个对我有用的简短程序中,我使用了线程,但是是否有更好的方法来完成此任务,或者是一种更好的代码?另外,Ctrl-C不会退出游戏手柄线程,即使我尝试使用tryexcept来允许键盘中断。 退出线程的好方法是什么? 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()

0 个答案:

没有答案