Skip to content

Instantly share code, notes, and snippets.

@johnwargo
Last active January 15, 2024 22:00
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save johnwargo/ea5edc8516b24e0658784ae116628277 to your computer and use it in GitHub Desktop.
Save johnwargo/ea5edc8516b24e0658784ae116628277 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
# Make sure you install required libraries:
# https://gpiozero.readthedocs.io/en/stable/installing.html
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)
@OpenSourceIronman
Copy link

@krahul9473
Copy link

I m agtting error.
Traceback (most recent call last):
File "relay-test.py", line 11, in
import gpiozero
ModuleNotFoundError: No module named 'gpiozero'

@johnwargo
Copy link
Author

@krahul9473 did you install the gpiozero library? It's not just there, you have to install it.

https://gpiozero.readthedocs.io/en/stable/installing.html

@krahul9473
Copy link

krahul9473 commented Aug 2, 2021 via email

@johnwargo
Copy link
Author

Well, its not going to work unless you install all required libraries. There's nothing I can to do to help here.

@krahul9473
Copy link

krahul9473 commented Aug 3, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment