0

运行以下简单代码时,我希望 [while True] 返回与 pir 运动传感器状态相关的 1 和 0 的无穷无尽的流。但是,一旦触发,即使动作结束,我也只能得到 1 秒。如果我做相反的事情(即,将循环放入 when_no_motion),我会得到一串 0... pir.value 似乎没有更新。

有什么线索吗?

提前致谢!

from signal import pause
from gpiozero import MotionSensor

pir = MotionSensor(4, queue_len=1)

def do_motion_detected():
  while True:
    print(pir.value)

pir.when_motion = do_motion_detected

pause()

还可能值得注意的是,当我尝试使用 GPIOZero Button 而不是 MotionSensor 时,它工作正常,给了我一个 1 和 0 的流,与 Button 值相关......

from signal import pause
from gpiozero import Button

clicker = Button(4)

def do_press_detected():
  while True:
    print(clicker.value)

clicker.when_pressed = do_press_detected

pause()
4

1 回答 1

0

我从未使用过这个图书馆,所以请谨慎使用

1)通过阅读文档,您应该使用“motion_detected”而不是“value”,因为“value”也连接到“queue_len”,基本上它不会返回 bool 运动/非运动,而是队列中所有值的平均值.

https://gpiozero.readthedocs.io/en/stable/api_input.html#gpiozero.MotionSensor

2)您的问题可能根本与编程无关,但可能是接线错误。也许您没有使用上拉/下拉电阻,结果,您的电线上只有噪声,导致永久 0 值。这称为“浮动”。换句话说,您的程序可以工作,但您的引脚上的信号是浮动的,因此您正在读取噪声。

https://grantwinney.com/using-pullup-and-pulldown-resistors-on-the-raspberry-pi/

3)我建议你使用标准的 GPIO 库并更接近金属。一旦熟悉了它,就可以使用更高级别的框架来控制 I/O。

额外说明:

不要使用

while True:
    print('something')

这只会从您的树莓派中窃取 CPU。你应该做的是检查采样频率——(你需要的或者你的库提供的)并将睡眠放在循环的末尾

import time
sampling_frequency = 50
while True:
    print('read from sensor')
    time.sleep( 1./(sampling_frequency*2))

#I multiply sampling_frequency by 2 due to Shannon frequency theorem

附注2:

函数when_motion是回调/事件处理程序。这意味着如果有运动,您定义的某些功能将被触发。你所拥有的并没有真正的意义。

这样的事情更有意义

...
def initialize_locking_doors():
    print('Motion was detected. Locking doors')
    #lock_doors....
    #leave the function

pir.when_motion = initialize_locking_doors
...
于 2019-08-05T09:43:29.147 回答