Skip to content

Instantly share code, notes, and snippets.

@prietopa
Created April 11, 2020 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prietopa/1f7c8ede319f65e3848e2da28e4279c6 to your computer and use it in GitHub Desktop.
Save prietopa/1f7c8ede319f65e3848e2da28e4279c6 to your computer and use it in GitHub Desktop.
Conect a relay to raspberry pi to control a light
#!/usr/bin/python
# from https://gist.githubusercontent.com/johnwargo/ea5edc8516b24e0658784ae116628277/raw/cb9eb3bcb2121b2a67b51a684a88e5f93a0ef4d0/relay-test.py
# A simple Python application for controlling a relay board from a Raspberry Pi
# The application uses the GPIO Zero library (https://gpiozero.readthedocs.io/en/stable/)
# The relay is connected to one of the Pi's GPIO ports, then is defined as an Output device
# in GPIO Zero: https://gpiozero.readthedocs.io/en/stable/api_output.html#outputdevice
import sys
import time
import gpiozero
# change this value based on which GPIO port the relay is connected to
RELAY_PIN = 26
# create a relay object.
# Triggered by the output pin going low: active_high=False.
# Initially off: initial_value=False
relay = gpiozero.OutputDevice(RELAY_PIN, active_high=False, initial_value=False)
def set_relay(status):
if status:
print("Setting relay: ON")
relay.on()
else:
print("Setting relay: OFF")
relay.off()
def toggle_relay():
print("toggling relay")
relay.toggle()
def main_loop():
# start by turning the relay off
set_relay(False)
while 1:
# then toggle the relay every second until the app closes
toggle_relay()
# wait a second
time.sleep(1)
if __name__ == "__main__":
try:
main_loop()
except KeyboardInterrupt:
# turn the relay off
set_relay(False)
print("\nExiting application\n")
# exit the application
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment