Python GPIO函数输入按钮在下降edg上切换

2024-04-16 23:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让一个脚本工作,其中一个按钮被监控,如果操作一次,然后打开一些东西。如果再次操作,请将其关闭。就像一个开关按钮。 我有它与下面的代码工作,但这并不好,因为它总是等待按钮边缘触发。所以while循环中的任何其他代码都不会执行。如果一个按钮被操作了,我该如何检查该功能,如果没有,则继续执行其余的代码。在

import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM) # using broadcomm pin numbers

GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)

prevWater = 0

def buttonControl ():
    global prevWater 
    # take a reading
    GPIO.wait_for_edge(21, GPIO.FALLING)
    prevWater = not prevWater
    return prevWater

while 1:
    waterButton = buttonControl ()
    if (waterButton == True):
        print ("Turn water on")
    if (waterButton == False):
        print ("Turn water off")
    # check what is returned from function
    print (waterButton)

# need to do other stuff here

GPIO.cleanup()

任何帮助都将不胜感激

我已尝试回拨如下所示

^{pr2}$

但我得到的错误如下所示

“文件”测试.py“,第19行,英寸GPIO.add_event_检测(21岁,GPIO.上升,callback=my\u callback)运行时错误:已为此GPIO通道启用冲突边缘检测


Tags: 代码importgpioif错误callback按钮边缘
1条回答
网友
1楼 · 发布于 2024-04-16 23:50:46

了解如何使用回调函数执行此操作,如下所示。这个脚本可以在按下按钮时打开和关闭LED。我现在唯一的问题是,即使加上脱弹时间,开关似乎也在弹跳。我听说开关上的一个小电容器可以阻止这一切。这个星期我要试一试

 import time
 import RPi.GPIO as GPIO


 GPIO.setmode(GPIO.BCM) # using broadcomm pin numbers

 GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
 GPIO.setup(17, GPIO.OUT)

 prevWater = 0

 def my_callback(channel):
     global prevWater
     prevWater = not prevWater
     return prevWater

 GPIO.add_event_detect(21, GPIO.RISING, callback=my_callback, bouncetime=200 )

 while 1:
     waterButton = prevWater
     if (waterButton == True):
         GPIO.output(17,GPIO.LOW)
     if (waterButton == False):
         GPIO.output(17,GPIO.HIGH)

 # need to do other stuff here

 GPIO.cleanup()

相关问题 更多 >