Skip to content

Instantly share code, notes, and snippets.

@kelixlabs
Forked from johnwargo/relay-test.py
Created November 2, 2018 11:34
Show Gist options
  • Save kelixlabs/a701f823dbb0c4036f0c938d7f4a3f21 to your computer and use it in GitHub Desktop.
Save kelixlabs/a701f823dbb0c4036f0c938d7f4a3f21 to your computer and use it in GitHub Desktop.
Simple Python app for controlling a relay through an GPIO Zero Output device
#!/usr/bin/python
# 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 = 18
# 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