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);

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


See gpiozero OutputDevice.


import gpiozero


# 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
  • Perfect. Thanks @joan. Didn't look far enough down in the documentation... :-/ – BoCoKeith Jan 23 at 18:27
  • Some relays are reversed so if turning the device on actually deactivates the relay (and vice-versa) then you want active_high=False) – ben_nuttall Jan 23 at 23:31
  • My relays are definitely "active low", @ben_nuttall. I added the circuit I am using to make them "active high" above. I appreciate the heads up, though. – BoCoKeith Jan 25 at 0:21

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.

  • Thanks for the info @Milliways. I can't add a picture in a comment, but I did include the circuit I'm using to drive the relay in my original post. An EE I'm definitely not, but it looks to me like this resolves the issue of 3.3V vs 5V you've noted. Yes? No? I will only be using one relay at a time (an irrigation system, not home control). Although I am currently feeding 5V to the relay from the RPi, though I will definitely change that. – BoCoKeith Jan 25 at 0:18
  • It is normal practice to add additional detail to your Question. That should be OK (and is one of the options I suggested) the 10kΩ does nothing. If powering from 5V there should be no reason you can't use the Pi 5V (although this negates any opto-isolation) – Milliways Jan 25 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.