编程语言
首页 > 编程语言> > python – TraceBack(最近调用最后一次)和GPIO.setmode(GPIO.BOARD)或GPIO.setmode(GPIO.BCM)错误

python – TraceBack(最近调用最后一次)和GPIO.setmode(GPIO.BOARD)或GPIO.setmode(GPIO.BCM)错误

作者:互联网

我一直在努力使用一个脚本,将Pi的BCM引脚17,27和10打开1秒,然后关闭1秒,依次100次.当我运行脚本时,LED1将打开,然后它会关闭,程序会因此错误而关闭:

Traceback (most recent call last):
  File "LedBlink.py", line 47, in <module>
    LED2Blink()
  File "LedBlink.py", line 27, in LED2Blink
    GPIO.setup(LED2, GPIO.OUT)
RuntimeError: Please set pin numbering mode using     GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)

import RPi.GPIO as GPIO
import time

LED1 = 17
LED2 = 27
LED3 = 10

GPIO.setmode(GPIO.BCM)

def LED1Blink():
        GPIO.setup(LED1, GPIO.OUT)
        GPIO.output(LED1,True) 
        time.sleep(1)  
        GPIO.output(LED1,False)
        time.sleep(1)
        GPIO.cleanup()

def LED2Blink():
        GPIO.setup(LED2, GPIO.OUT)
        GPIO.output(LED2,True) 
        time.sleep(1)  
        GPIO.output(LED2,False)
        time.sleep(1)
        GPIO.cleanup()

def LED3Blink():
        GPIO.setup(LED3, GPIO.OUT)
        GPIO.output(LED3,True) 
        time.sleep(1)  
        GPIO.output(LED3,False)
        time.sleep(1)
        GPIO.cleanup()

i = 0
while i < 100:
       LED1Blink()
       LED2Blink()
       LED3Blink()
       i + 1
else:
       print "finished loop"

解决方法:

问题是你在每个方法的末尾调用GPIO.cleanup().如documentation中所述,请注意GPIO.cleanup()也会清除正在使用的引脚编号系统.您想要的是GPIO.cleanup(通道),其中通道对应于脚本中的LED1,LED2,LED3.

最佳做法是仅设置和清除信道,例如,

import RPi.GPIO as GPIO
import time

LED1 = 17
LED2 = 27
LED3 = 10

GPIO.setmode(GPIO.BCM)
GPIO.setup(LED1, GPIO.OUT)
GPIO.setup(LED2, GPIO.OUT)
GPIO.setup(LED3, GPIO.OUT)

def LED1Blink():
        GPIO.output(LED1,True) 
        time.sleep(1)  
        GPIO.output(LED1,False)
        time.sleep(1)

def LED2Blink():
        GPIO.output(LED2,True) 
        time.sleep(1)  
        GPIO.output(LED2,False)
        time.sleep(1)

def LED3Blink():
        GPIO.output(LED3,True) 
        time.sleep(1)  
        GPIO.output(LED3,False)
        time.sleep(1)

i = 0
if i < 100:
       LED1Blink()
       LED2Blink()
       LED3Blink()
       i + 1
else:
       GPIO.cleanup()
       print "finished loop"

标签:gpio,python,microcontroller
来源: https://codeday.me/bug/20191008/1871019.html