Control Relay via gpio on Raspberry Pi using gpiod with library libgpiod v2

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 gpiod

PI_PIN = 23

GPIOCHIPSET = "/dev/gpiochip0"

 

GPIOLINE=gpiod.request_lines(GPIOCHIPSET,consumer="relaygarage",config={

  PI_PIN: gpiod.LineSettings(

    direction=gpiod.line.Direction.OUTPUT,bias=gpiod.line.Bias.PULL_UP,output_value=gpiod.line.Value.ACTIVE)

})

GPIOLINE.set_value(PI_PIN, gpiod.line.Value.ACTIVE)

GPIOLINE.set_value(PI_PIN, gpiod.line.Value.INACTIVE)

sleep(0.3)

GPIOLINE.set_value(PI_PIN, gpiod.line.Value.ACTIVE)

GPIOLINE.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 bottem in Euro