我正在尝试在Raspberry Pi上学习Python和GPIO的同时制作一个“游戏”。这就是我的ATM:
while playing == 1:
if (GPIO.input(9) == 0):
GPIO.output(18, GPIO.LOW)
print("Well done!!")
time.sleep(1)
else:
print("Wrong!")
lives = lives - 1
time.sleep(1)
playing = 0
现在,我的问题是该程序正在命令if语句并直接进入else(正如您所期望的那样),但是,我希望程序在if语句的第一部分等待一秒钟,然后去别的地方。
提前致谢!
答案 0 :(得分:1)
也许你可以像这样重写它:
while playing == 1:
for _ in range(10):
if GPIO.input(9) == 0:
GPIO.output(18, GPIO.LOW)
print("Well done!!")
break
time.sleep(0.1)
else:
print("Wrong!")
lives = lives - 1
这将GPIO引脚分开十次100ms。如果GPIO引脚在十次尝试期间保持高电平,则会else
被击中。
(如果您没有遇到Python的for
- else
构造,请参阅Why does python use 'else' after for and while loops?。)
或者,您可以使用GPIO
模块的更高级功能,例如边缘检测和回调。请参阅documentation。