我正在从事这个项目与运动传感器,其中我希望有监视器关闭时,有没有运动后,一定的时间过去了。但每次有动作时,我都希望计时器重置。
我有打开和关闭监视器的代码,但是我如何添加计时器呢?
任何帮助都将不胜感激。我的代码:
from gpiozero import MotionSensor
import time
from subprocess import call
pir = MotionSensor(4)
while True:
pir.wait_for_motion()
print("Screen On")
call(["/usr/bin/vcgencmd", "display_power", "1"])
time.sleep(30)
pir.wait_for_no_motion()
print("Screen Off")
call(["/usr/bin/vcgencmd", "display_power", "0"])
time.sleep(1)发布于 2020-04-12 18:35:08
除了wait_for_motion(),gpiozero还提供了一个变量motion_detected。下面的代码将变量startpoint设置为自1970年1月1日以来的当前时间。然后,它启动一个循环,该循环:
startpoint变量设置回当前时间(当然,该时间将不同于以前的时间),并在startpoint变量比当前时间早30秒时打开startpoint。由于每次运动检测都会重置此变量,因此我们知道自上次运动检测以来必须至少有30秒。如果是,则关闭显示。startpoint = time.time() while True: if pir.motion_detected: startpoint = time.time() call(["/usr/bin/vcgencmd", "display_power", "1"]) print("Display on") elif time.time() > (startpoint+30): call(["/usr/bin/vcgencmd", "display_power", "0"]) print("Display off")
发布于 2020-04-12 18:49:48
您也可以使用threading来实现这一点。
from enum import Enum
from gpiozero import MotionSensor
from subprocess import call
from threading import Timer
from time import sleep
from typing import Optional
pir = MotionSensor(4)
timer: Optional[Timer] = None
class MonitorState(Enum):
ON = "1"
OFF = "0"
def set_monitor_state(state: str):
call(["/usr/bin/vcgencmd", "display_power", state.value])
def start_timer():
global timer
if timer:
timer.cancel()
timer = Timer(30, set_monitor_state, (MonitorState.OFF,))
timer.start()
start_timer()
while True:
pir.wait_for_motion()
start_timer()
set_monitor_state(MonitorState.ON)我不确定在回调返回时或之前,Timer是否真的被算作done。在第一种情况下,当计时器运行时调用set_monitor_state(MonitorState.ON)时,您可能会遇到麻烦,因为它在另一个线程上执行回调。在这种情况下,您可能希望使用锁定。
https://stackoverflow.com/questions/61169664
复制相似问题