首页 > 解决方案 > Raspberry Pi 按钮 LED 随机触发器

问题描述

我编写了这段代码来检查连接到 GPIO 引脚 13 的按钮是否被按下。我的电路从 3.3v 电源到 220ohm 电阻再到按钮和 GPIO 引脚 13。我的 LED 电路本身工作得很好。每当我运行此脚本时,LED 似乎会随机关闭和打开,并且无需我按下按钮即可打印相关文本。这似乎是完全随机的。

当我按下按钮时,要么未检测到输入,要么检测到多个输入。

这是我的源代码:

#Turn LED on and off with push button
#By H
#Start date: February 12th, 2021
#End dat

#Importing GPIO and time libraries for delays and use of RPi3B GPIO pins
import RPi.GPIO as GPIO
import time

#Setting GPIO mode to BOARD in order to use on-board GPIO numbering
GPIO.setmode(GPIO.BOARD)

#Setting 13 as an input for the push button
#Setting 11 as an output for the LED
GPIO.setup(13,GPIO.IN) 
GPIO.setup(11,GPIO.OUT)

#Infinite while statement so the script doesnt end, containing checks for the button being pushed, and turning the LED on/off
while True:
    print ("Off")
    GPIO.output(11, GPIO.LOW)
    while GPIO.input(13) == 1:
        time.sleep(0.1) 
    print ("On")
    GPIO.output(11, GPIO.HIGH)
    while GPIO.input(13) == 0:
        time.sleep(0.1)     

我还使用了来自 Raspberry Pi 论坛的脚本,该脚本使用带有 GPIO_EVENT_DETECT 的上拉和下拉电阻器以及 2 个用于打开和关闭的单独按钮。每当我使用该代码按下任一按钮时,我都会快速连续获得 2,3 甚至更多输入,即使我只按下了一次按钮。

这是源代码:

import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)

btn_input = 11;# button to monitor for button presses.
btn_input2 = 13;# 2nd button to monitor for button presses.
LED_output = 15;   # LED to light or not depending on button presses.

# GPIO btn_input set up as input.
GPIO.setup(btn_input, GPIO.IN)
GPIO.setup(btn_input2, GPIO.IN)
GPIO.setup(LED_output, GPIO.OUT)

# handle the button event
def buttonEventHandler_rising (pin):
    # turn LED on
    GPIO.output(LED_output,True)
    print("on")
    
def buttonEventHandler_falling (pin):
    # turn LED off
    GPIO.output(LED_output,False)
    print("off")


# set up the event handlers so that when there is a button press event, we
# the specified call back is invoked.
GPIO.add_event_detect(btn_input, GPIO.RISING, callback=buttonEventHandler_rising) 
GPIO.add_event_detect(btn_input2, GPIO.FALLING, callback=buttonEventHandler_falling)
 
# we have now set our even handlers and we now need to wait until
# the event we have registered for actually happens.
# This is an infinite loop that waits for an exception to happen and
# and when the exception happens, the except of the try is triggered
# and then execution continues after the except statement.
try:  
    while True : pass  
except:
    print("Stopped")
    GPIO.cleanup()      

我该如何解决这些问题,以便我可以使用 1 个单个按钮来打开和关闭 LED,按下按钮将其打开,释放后它保持打开状态,再次按下将关闭它,释放后保持关闭?

标签: pythonraspberry-pigpio

解决方案


尝试设置 pull_up_down 属性GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)并移除电阻。使用电阻器可能不会迫使张力上升到足够高,因为电流会使其下降,这可能是您出现这种不稳定行为的原因。如果内部电阻在 50k 左右,则应如此。尝试查看 gpiozero Button-led的食谱。gpiozero 还有一个去抖动参数。

LED 需要电阻器,因为它只能处理 0.7v 的电压。要达到 3.3v 或 5v,您需要电阻器来降低附加电压。电阻越低,LED 越亮。如果它太高,则不会有足够的电流使 LED 亮起。


推荐阅读