我正在尝试制作一款“游戏”,同时在 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 语句的第一部分等待一秒钟,然后去else。
提前致谢!
请您参考如下方法:
也许你可以这样重写它:
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
这会以 100 毫秒的间隔轮询 GPIO 引脚十次。如果 GPIO 引脚在十次尝试中都保持高电平,则命中 else。
(如果您还没有遇到过 Python 的 for-else 结构,请参阅 Why does python use 'else' after for and while loops?。)
或者,您可以使用 GPIO 模块的更高级功能,例如边缘检测和回调。查看documentation .
