GPIO设置错误和键盘中断 - Python

时间:2017-04-28 11:43:57

标签: python raspberry-pi raspbian gpio keyboardinterrupt

我已经编写了一个代码来打开继电器2秒,然后关闭,但我遇到了问题。

首先一个程序运行我得到以下错误,但GPIO已设置:

`Traceback (most recent call last):
  File "relay_control.py", line 16, in <module>
    GPIO.output(2, GPIO.HIGH)
RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)`

我的第二个问题是我想设置KeyboardInterrupt当我使用except KeyboardInterrupt:时我得到一个错误并且没有任何运行,如果我把它留下来它会经历一个循环并退出(如预期的那样) :

    File "relay_control.py", line 30
    except KeyboardInterrupt:
         ^
SyntaxError: invalid syntax

我不确定有什么问题,完整的代码如下:

import RPi.GPIO as GPIO
from time import sleep

    GPIO.setmode(GPIO.BCM)

    # Set relay pins as output
    GPIO.setup(2, GPIO.OUT)
    GPIO.setup(3, GPIO.OUT)
    GPIO.setup(4, GPIO.OUT)
    GPIO.setup(17, GPIO.OUT)

    while (True):

        # Turn all relays ON
        GPIO.output(2, GPIO.HIGH)
        GPIO.output(3, GPIO.HIGH)
        GPIO.output(4, GPIO.HIGH)
        GPIO.output(17, GPIO.HIGH)
        # Sleep for 5 seconds
        sleep(2)
        # Turn all relays OFF
        GPIO.output(2, GPIO.LOW)
        GPIO.output(3, GPIO.LOW)
        GPIO.output(4, GPIO.LOW)
        GPIO.output(17, GPIO.LOW)
        # Sleep for 5 seconds
        sleep(2)

    except KeyboardInterrupt:
        print "Quit"
        GPIO.cleanup()

2 个答案:

答案 0 :(得分:1)

以某种方式修复键盘中断不会出现任何错误:

import RPi.GPIO as GPIO
from time import sleep

# The script as below using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)

# Set relay pins as output
GPIO.setup(2, GPIO.OUT)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)

try:
        while (True):

            # Turn all relays ON
            GPIO.output(2, GPIO.HIGH)
            GPIO.output(3, GPIO.HIGH)
            GPIO.output(4, GPIO.HIGH)
            GPIO.output(17, GPIO.HIGH)
            # Sleep for 5 seconds
            sleep(2)
            # Turn all relays OFF
            GPIO.output(2, GPIO.LOW)
            GPIO.output(3, GPIO.LOW)
            GPIO.output(4, GPIO.LOW)
            GPIO.output(17, GPIO.LOW)
            # Sleep for 5 seconds
            sleep(2)

except KeyboardInterrupt:
    print "Quit"
    GPIO.cleanup()

答案 1 :(得分:0)

这是正确的代码:

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

# Set relay pins as output
GPIO.setup(2, GPIO.OUT)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)

while (True):
    try:
        # Turn all relays ON
        GPIO.output(2, GPIO.HIGH)
        GPIO.output(3, GPIO.HIGH)
        GPIO.output(4, GPIO.HIGH)
        GPIO.output(17, GPIO.HIGH)
        # Sleep for 5 seconds
        sleep(2)
        # Turn all relays OFF
        GPIO.output(2, GPIO.LOW)
        GPIO.output(3, GPIO.LOW)
        GPIO.output(4, GPIO.LOW)
        GPIO.output(17, GPIO.LOW)
        # Sleep for 5 seconds
        sleep(2)

    except KeyboardInterrupt:
        print "Quit"
        GPIO.cleanup()