0

I am using this relay module with Raspi zero. https://www.amazon.co.jp/gp/product/B083LRNXBJ/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

And I am using gpiozero to control relay.

import gpiozero
import time

RELAY_PIN = 14

relay = gpiozero.OutputDevice(RELAY_PIN, active_high=True, initial_value=False)
def main():
  try:
    while True:
      print('on')
      relay.on()
      time.sleep(3)
      print('off')
      relay.off()
      print(relay.value)
      time.sleep(3)
  except KeyboardInterrupt:
    # relay.off()
    print("exit")
    exit(1)

if __name__ == '__main__':
  main()

But the problem is relay never turns off until loop exits, or we exit program. If there is no loop, relay turns off with relay.off() easily.

EDIT: so even this doesnt work:

def main():
  try:
    relay.on()
    time.sleep(3)
    relay.off()

    while True:
      print ('blah blah going on and relay is still ON..')
  except KeyboardInterrupt:
    # relay.off()
    print("exit")
    exit(1)

Jaydeep
  • 446
  • 1
  • 6
  • 17
  • You waited more than 3 seconds before exiting the program? Do you see the `'off'` output? It's obvious, but just to make sure the time.sleep() doesn't fool you. – Sparkofska Mar 26 '21 at 12:56
  • Did you check the wiring? It must match the `active_high=True` mode – Sparkofska Mar 26 '21 at 12:59
  • @Sparkofska I edited question. I dont think time.sleep has any connection. if there is no while loop, relay turns off. and about wiring what is special about active_high? I correctly connected vcc, gnd and in cables to raspi. And for extra note: It works fine with LED , only relay has this issue. – Jaydeep Mar 26 '21 at 13:53
  • Does this works for you ? https://gist.github.com/johnwargo/ea5edc8516b24e0658784ae116628277 – rok Mar 26 '21 at 15:24
  • @rok nope. same behavior. relay turns off only when I exit program... – Jaydeep Mar 26 '21 at 16:25
  • are you sure that relay works properly with a raspberry? it looks like a 5V relay and they have many issues with raspberry, read [here](https://www.raspberrypi.org/forums/viewtopic.php?f=91&t=83372&p=1225448#p1225448) – rok Mar 26 '21 at 17:02

1 Answers1

0

I had a same experience. And the reason is that the declaration of outputDevice already turns on the circuit. instead of using .on() function, just declare the outputDevice everytime when you need.

try this.

def main():
  try:
    while True:
      print('on')
      relay = gpiozero.OutputDevice(RELAY_PIN, active_high=True, initial_value=False)
      time.sleep(3)
      print('off')
      relay.off()
      print(relay.value)
      time.sleep(3)
  except KeyboardInterrupt:
    # relay.off()
    print("exit")
    exit(1)