我正在树莓派上配置一些LED和按钮,并且在运行脚本时,系统会警告我某个通道已在使用中。我尝试寻找解决方案,而技巧是在finally子句中进行GPIO.Cleanup()
。我尝试过,但是一直失败。知道为什么吗?错误指向GPIO.setup(button_pin, GPIO.IN)
,但不确定在我的try子句中添加这些代码行吗?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
import time
# Hide Warnings
# GPIO.setwarnings(False)
# Assign GPIO pin numbers
button_pin = 3 # Input Pin
button_led = 14 # Output Pin
green_led = 22 # Output Pin
red_led = 27 # Output Pin
# ir_receiver_pin = 17
# Use BCM pin numbering
GPIO.setmode(GPIO.BCM)
# 1. GPIO Setup
GPIO.setup(button_pin, GPIO.IN)
GPIO.setup(button_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)
GPIO.setup(red_led, GPIO.OUT)
# 2. Button Led Behaviour on Startup
def button_led_on():
GPIO.output(button_led, GPIO.HIGH)
def button_led_off():
GPIO.output(button_led, GPIO.LOW)
def button_flicker_startup():
a = 1
while a < 4:
button_led_on()
time.sleep(0.3)
button_led_off()
time.sleep(0.3)
a = a + 1
button_led_on() # LED is high when Pi is on
# 3. Define front led behaviour on startup
def green_led_on():
GPIO.output(green_led, GPIO.HIGH)
def green_led_off():
GPIO.output(green_led, GPIO.LOW)
def red_led_on():
GPIO.output(red_led, GPIO.HIGH)
def red_led_off():
GPIO.output(red_led, GPIO.LOW)
def boot_flicker():
time.sleep(1.0)
green_led_on()
time.sleep(0.5)
green_led_off()
time.sleep(0.2)
green_led_on()
time.sleep(0.3)
green_led_off()
red_led_on()
time.sleep(0.3)
red_led_off()
time.sleep(0.2)
green_led_on() # LED is high when Pi is on
# 4. Main program
try:
button_flicker_startup()
boot_flicker()
GPIO.wait_for_edge(button_pin, GPIO.FALLING)
os.system("sudo shutdown -h now")
except:
pass
finally:
GPIO.cleanup()
我可以使用GPIO.setwarnings(False)
,但这只是隐藏错误并希望避免这种情况。
编辑:我的Raspberry Pi使用的是Hifiberry dac,后者使用GPIO 2和3进行配置。可能与此有关吗?
答案 0 :(得分:0)
我将主要内容更改为此:
x = True
try:
while x:
button_flicker_startup()
boot_flicker()
GPIO.wait_for_edge(button_pin, GPIO.FALLING)
os.system("sudo shutdown -h now")
except:
pass
finally:
x = False
GPIO.cleanup()
由于功能正在运行,现在我们迫使它们停止运行,然后进行清理。 我已使用此视频来帮助我https://www.youtube.com/watch?v=LEi_dT9KDJI&t=257s: 如果我是您,我会看的,我会深入了解您的需求/想要的事情。