Raspberry Pi 按钮 LED 随机触发

Raspberry Pi push button LED random triggers

我编写这段代码是为了检查连接到 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,按下按钮将其打开,松开后它会保持打开状态,再次按下将关闭它, 释放后不在?

尝试设置 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 点亮。