我正在编写一个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)
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)