在GPIO中打破循环

时间:2017-04-27 22:06:21

标签: python raspberry-pi interrupt keyboardinterrupt

我正在使用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)

我应该在哪里添加键盘中断命令?

1 个答案:

答案 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)
相关问题