0

我正在使用这个带有 Raspi 零的继电器模块。 https://www.amazon.co.jp/gp/product/B083LRNXBJ/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

gpiozero用来控制继电器。

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

但问题是继电器永远不会关闭,直到循环退出,或者我们退出程序。relay.off()如果没有回路,继电器很容易关闭。

编辑:所以即使这样也行不通:

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)

4

1 回答 1

0

我也有同样的经历。原因是 outputDevice 的声明已经打开了电路。而不是使用 .on() 函数,只需在每次需要时声明 outputDevice 。

尝试这个。

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)

于 2021-04-02T04:19:20.400 回答