问题描述
我将这个继电器模块与 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)
解决方法
我也有过同样的经历。 原因是 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)