Control Relay via gpio on Raspberry Pi

To control a relay on Raspberry Pi GPIO use the following Python script.

This is using the gpiod library which is supported on all models of the Raspberry Pi!

The following script is used to switch a relay for one second to on-off (using GPIO port 23). You can change it to just set one status by removing the sleep line and one line_set_value line..

 

gpiorelay23.py

------------------------------------------------------------------------------

#!/usr/bin/python3

from time import sleep
import os.path
#import gpiod
#from gpiod import Chip, LINE_REQ_DIR_IN, LINE_REQ_DIR_OUT, LINE_REQ_FLAG_BIAS_PULL_DOWN, LINE_REQ_FLAG_BIAS_PULL_UP, Line
from gpiod import Chip, LINE_REQ_DIR_OUT, Line

PI_PIN = 23
path = '/dev/gpiochip4'
check_file = os.path.exists(path)
if (check_file):
    GPIOCHIPSET = 'gpiochip4'
else:
    GPIOCHIPSET = 'gpiochip0'

chip = Chip(GPIOCHIPSET, Chip.OPEN_BY_NAME)
line = chip.get_line(PI_PIN)

try:
    line.request(consumer="relaysend", type=LINE_REQ_DIR_OUT)
except OSError:
    sleep(2)
    try:
        line.request(consumer="relaysend", type=LINE_REQ_DIR_OUT)
    except OSError:
        sleep(2)
        try:
            line.request(consumer="relaysend", type=LINE_REQ_DIR_OUT)
        except OSError:
            print("Error", end='')
        else:
            line.set_value(0)
            sleep(1)
            line.set_value(1)
    else:
        line.set_value(0)
        sleep(1)
        line.set_value(1)
else:
    line.set_value(0)
    sleep(1)
    line.set_value(1)

line.release()
exit()

#2 The following script is used to switch a relay for one second to on-off (using GPIO port 23).

cat gpiorelay23.py

------------------------------------------------------------------------------

 

  Donate now via the Paypal button on the top in US Dollar and on the bottom in Euro