GPIO瞬时按钮控制继电器

时间:2016-05-26 10:45:32

标签: python raspberry-pi gpio

我想知道是否可以让我的瞬间按钮控制Python中的继电器而我按住按钮是什么时候?

实质上,当按下按钮时,继电器开启,当按钮松开时,继电器关闭。

目前,我可以使用一个小的python脚本控制继电器,将其打开持续5个秒:

relay.py:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)

GPIO.output(4, GPIO.LOW)
time.sleep(5)
GPIO.output(4, GPIO.HIGH)
GPIO.cleanup()

print "Done!"

能够跟踪瞬间按钮何时被按下:

button.py:

import os
from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN)

while True:
        if (GPIO.input(25) == False):
                print "Button being pushed!"
        GPIO.output(4, GPIO.LOW)
        sleep(0.025)

我试图将这两者结合在一起:

import os
from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN)
GPIO.setup(4, GPIO.OUT)

while True:
        if (GPIO.input(25) == False):
                print "Button being pushed!"
                GPIO.output(4, GPIO.LOW)
        sleep(0.025)
        GPIO.output(4, GPIO.HIGH)

但无济于事。任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:1)

当然,这应该可以解决问题。我没有测试它,所以可能需要一些小的编辑。

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

# Added a software pull-up here for increased stability
GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(4, GPIO.OUT)
# The relay seems to be active low. Default to off.
GPIO.output(4, GPIO.HIGH)

# This function is run every time the button state changes 
# from low to high or high to low (GPIO.BOTH)
def callback_func(pin):
    # The button transitioned to high (released) 
    if GPIO.input(pin):
        # Relay off
        GPIO.output(4, GPIO.HIGH)
    else:
        # The button went low (it was pressed). Relay on.
        GPIO.output(4, GPIO.LOW)

# Set up threaded event detection (no constant polling of pin states).
# Fires on both high-to-low and low-to-high state changes.
GPIO.add_event_detect(25, GPIO.BOTH, callback=callback_func)

def main():
    while True:
        print "Not blocking! You're free to do other stuff here"
        time.sleep(5)

if __name__ == "__main__":
    main()

如果释放按钮时GPIO.PUD_UP没有引起上升沿,则必须在VCC上添加一个电阻。无论如何这样做是个好主意,因为即使软件失败,它也能确保继电器保持默认状态。

一个丑陋的版本,当按下按钮时不断写入继电器GPIO,但应该没有上拉:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(4, GPIO.OUT)
GPIO.output(4, GPIO.HIGH)

def callback_func(pin):
    while not GPIO.input(pin):
        GPIO.output(4, GPIO.LOW)
    GPIO.output(4, GPIO.HIGH)

GPIO.add_event_detect(25, GPIO.FALLING, callback=callback_func, bouncetime=100)

def main():
    while True:
        print "Not blocking! You're free to do other stuff here"
        time.sleep(5)

if __name__ == "__main__":
    main()