我正在使用while循环定期为LED供电。我想正常运行循环,但是当按下某个键时让它中断并清理。
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(12,GPIO.OUT)
while True:
GPIO.output(12,GPIO.HIGH)
time.sleep(0.2)
GPIO.output(12,GPIO.LOW)
time.sleep(0.2)
我应该在哪里添加键盘中断命令?
答案 0 :(得分:0)
好 Ctrl - C 引发KeyboardInterrupt。所以,你只需要抓住它:
while True:
try:
#code
except KeyboardInterrupt:
break
要捕获所有其他错误,请使用:
except Exception as ex : # catch other exceptions #
print(ex)
因此,应用于您的代码:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(12,GPIO.OUT)
while True:
try:
GPIO.output(12,GPIO.HIGH)
time.sleep(0.2)
GPIO.output(12,GPIO.LOW)
time.sleep(0.2)
except KeyboardInterrupt:
break
except Exception as ex : # catch other exceptions #
print(ex)