RuntimeError (in Raspberry Pi) 在定义的变量处产生

RuntimeError (in Raspberry Pi) produced at a defined variable

我在 Python 2.7 和 Raspberry Pi 中遇到以下运行时错误:

Traceback (most recent call last):
File "ldrmqtt.py", line 96, in <module>
 main()
File "ldrmqtt.py", line 72, in main
 ldrData= rc_time(pin_to_circuit)
File "ldrmqtt.py", line 53, in rc_time
 GPIO.setup(pin_to_circuit, GPIO.OUT)
RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)

我已将 LDR 连接到我的 Raspberry Pi,我正尝试使用 MQTT 代理将值发送到 Thingspeak。我正在使用 Python 2.7.9

这是一个代码片段:

GPIO.setmode(GPIO.BOARD)

pin_to_circuit=7

 def rc_time (pin_to_circuit):
    count=0
    GPIO.setup(pin_to_circuit, GPIO.OUT)
    GPIO.output(pin_to_circuit, GPIO.LOW)
    time.sleep(0.15)
    GPIO.setup(pin_to_circuit, GPIO.IN)

    while(GPIO.input(pin_to_circuit) == GPIO.LOW):
        count +=1
    return count


try:
    while True:
        print rc_time(pin_to_circuit)
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

def main():
    print 'starting...'
    ldrData= rc_time(pin_to_circuit)
    tPayload= "field1=" % ldrData

    while True:
        try:
            publish.single(topic, payload=tPayload, hostname=mqttHost, 
            port=tPort, tls=tTLS, transport= tTransport)

        except KeyboardInterrupt:
            break
        except:      
            print: 'Error publishing the data'


 #call main
  if __name__=='__main__':
   main()

您必须为 GPIO 端口设置编号模式:

GPIO.setmode(GPIO.BCM)
  1. GPIO.BOARD – 板编号方案。管脚编号遵循接头 P1 上的管脚编号。

  2. GPIO.BCM – Broadcom 芯片特定的引脚号。这些引脚编号遵循 Raspberry Pi 的 Broadcom 芯片大脑定义的较低级别的编号系统。

从报错来看,好像需要设置GPIO.setmode.

import RPi.GPIO as GPIO  

# for GPIO numbering, choose BCM  
GPIO.setmode(GPIO.BCM)  

# or, for pin numbering, choose BOARD  
GPIO.setmode(GPIO.BOARD)  

# but you can't have both, so only use one!!!  

这里有一篇很好的文章:http://raspi.tv/2013/rpi-gpio-basics-4-setting-up-rpi-gpio-numbering-systems-and-inputs