简体   繁体   中英

Relay control with Raspberry Pi and Python3

below is a section of code I am using to control a relay to open electric gates via a relay which is controlled via pin 7 on a raspberry pi GPIO. The gates only need a momentary voltage (via the relay contacts) to open.

My question is, what do I need to add to this code to make the relay only switch on for 0.5 Seconds when pin 7 goes high. This would enable relay to return to the off state and then wait for the next time GPIO pin 7 goes high, the gates do not need any commands from the GPIO to close after a certain time, they close under the control of the separate gate control system.

if name=="gate":
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(int(7), GPIO.OUT)   ## Setup GPIO Pin to OUTPUT
GPIO.output(int(7), state) ## State is true/false

Many thanks

Peter

In this example I will use gpiozero library instead of RPi.GPIO because I like the way, how this library handle events.

from gpiozero import Button, OutputDevice
from time import sleep
from signal import pause

buttonPin = 4
relayPin = 7

button = Button(buttonPin)
button.when_pressed = ButtonPressedCallback
relay = OutputDevice(relayPin)

def ButtonPressedCallback():
    relay.on()
    sleep(0.5)
    relay.off()

pause()

I hope, I understood your question good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM