0

I am writing a Python app on my RPi to manage an 8-port Sainsmart relay. All that I need to do operate a port on that relay is to change the state on a GPIO pin to either low or high. I cannot find an obvious gpiozero object to simply change the state of a pin, though I can control it by pretending that it is an LED, e.g.:

import time
from gpiozero import LED

led = LED(27); led.on() time.sleep(10) led.off()

Is there a better way to do this? (I was looking at the pin factory stuff but that looks much more complicated...)

Also, I'd like to be able to read the state of said GPIO pin if it is possible (i.e. confirm the state of the pin).

If anyone cares, I have wired the relays to the RPi using this circuit (from Sainsmart) which converts them from "active low" to "active high":

enter image description here

BoCoKeith
  • 137
  • 1
  • 8

3 Answers3

1

See gpiozero OutputDevice.

E.g.

import gpiozero

RELAY_PIN = 4

Triggered by the output pin going high: active_high=True

Initially off: initial_value=False

relay = gpiozero.OutputDevice(RELAY_PIN, active_high=True, initial_value=False)

relay.off() # switch off

relay.on() # switch on

print(relay.value) # see if on or off

joan
  • 71,852
  • 5
  • 76
  • 108
1

The code Joan posted will work, but that does not mean the relays will.

These relay modules are unsuitable for the Pi as they are only controllable from 5V.
Attempting to run them risks damage to the Pi and they do not work reliably.

Can you use a 5V Relay Module with the Pi? describes these and suggests modifications to make them work.

In addition you could not use 8 as this would exceed the rating of the Pi GPIO.

Milliways
  • 62,573
  • 32
  • 113
  • 225
0

One thing for total noobs trying to use this code "as is" . It does work, but the relay wont do anything because the script exits too fast. If there is an LED on the relay board, you may see it blink once, very fast.

To actually see the relay turn on I had to add this code: At the top:

import sys
import time

Then at the end:

time.sleep(5)

This will make the script wait after turning the relay on for 5 seconds. Then the script will exit and the relay will turn off again.

Of course this may be very obvious to anyone with scripting knowledge, but for me, I was scratching my head and researching, until I found out from another script: https://gist.github.com/johnwargo/ea5edc8516b24e0658784ae116628277#file-relay-test-py