【发布时间】:2021-02-12 11:19:05
【问题描述】:
我编写此代码是为了检查连接到 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,按下按钮将其打开,释放后它保持亮起,再次按下它将关闭它,保持发布后关闭?
【问题讨论】:
-
您可能希望将此问题移至raspberrypi.stackexchange.com,特别是因为您的问题的某些方面可能与您项目的物理配置有关。关于在单个按钮按下时注册多个事件,请查找有关 debouncing 的信息。
-
您想研究“去抖动”。此 q/a 解决了这些主题:raspberrypi.stackexchange.com/questions/118349/…
标签: python raspberry-pi gpio