树莓派按钮 LED 随机触发

时间:2021-02-12 11:19:05

标签: python raspberry-pi gpio

我编写此代码是为了检查连接到 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,按下按钮将其打开,释放后保持亮起,再次按下将关闭它,保持发布后关闭?

1 个答案:

答案 0 :(得分:0)

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