首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用while循环时,带有gpiozero中继的Raspberri pi挂起

使用while循环时,带有gpiozero中继的Raspberri pi挂起
EN

Stack Overflow用户
提问于 2021-03-26 20:26:23
回答 1查看 61关注 0票数 0

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

我正在使用gpiozero来控制继电器。

代码语言:javascript
复制
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()关闭。

编辑:所以即使这样也不能工作:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2021-04-02 12:19:20

我也有过同样的经历。原因是outputDevice的声明已经开启了电路。不使用.on()函数,只要在需要的时候声明outputDevice即可。

尝尝这个。

代码语言:javascript
复制
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)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66816942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档