使用Wiimote按钮按下Python退出循环

时间:2016-01-06 18:38:33

标签: python led wiimote

我正在编写一个python脚本,它将使用cwiid库通过Wiimote控制LED。该程序识别wiimote并且能够启动循环,但是当用户按下" B"时,它不会让我停止循环。在遥控器上。这是相关代码,如果需要,我可以提供其余的脚本。感谢。

  buttons = wii.state['buttons']

...

  if (buttons & cwiid.BTN_A):
    print 'Button A pressed'
    print 'Press B to cancel loop'
    keepRunning = True
    while keepRunning:
        blink(32)#5v green
        blink(38)#5v yellow
        blink(36)#5v blue
        blink(40)#5v red
        blink(37)#3v3 green
        blink(35)#3v3 yellow
        blink(33)#3v3 blue
        blink(31)#3v3 red
        if (buttons & cwiid.BTN_B):
            keepRunning  = False
    time.sleep(button_delay)

以下是Stuart回答的固定循环

  if (buttons & cwiid.BTN_A):
    print 'Button A pressed'
    print 'Press B to cancel loop'
    keepRunning = True
    while keepRunning:
        blink(32)#5v green
        blink(38)#5v yellow
        blink(36)#5v blue
        blink(40)#5v red
        blink(37)#3v3 green
        blink(35)#3v3 yellow
        blink(33)#3v3 blue
        blink(31)#3v3 red
        buttons = wii.state['buttons']#added in this line
        if (buttons & cwiid.BTN_B):
            keepRunning  = False
    time.sleep(button_delay)

1 个答案:

答案 0 :(得分:1)

wii.state['buttons']似乎是一个数字,因此将其存储在变量buttons中意味着当用户按下不同的按钮组合时不再更新它。

要解决此问题,只需将buttons替换为每次wii.state['buttons']的直接引用。

您可能需要考虑检查每个blink后是否按下了B,如下所示:

from itertools import cycle
...
if wii.state['buttons'] & cwiid.BTN_A:
    print 'Button A pressed'
    print 'Press B to cancel loop'
    for colour in cycle([32, 38, 36, 40, 37, 35, 33, 31]):
        blink(colour)
        if wii.state['buttons'] & cwiid.BTN_B:
            break
    time.sleep(button_delay)