繁体   English   中英

在我的代码中添加计时器时遇到问题

[英]I am having trouble adding timer to my code

我正在使用运动传感器进行这个项目,我希望在经过一定时间后没有运动时关闭显示器。 但是每次有动作时,我都希望计时器重置。

我有用于通过运动打开和关闭显示器的代码,但是如何添加计时器?

任何帮助将不胜感激。 我的代码:

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)

除了wait_for_motion()之外,gpiozero 还提供了一个变量motion_detected 下面的代码设置一个变量, startpoint为自 1970 年 1 月 1 日以来的当前时间(以秒为单位)。 然后它开始一个循环:

  • 检查是否检测到运动 - 如果是,则将startpoint变量设置回当前时间(当然,这将与以前不同)并打开显示器。
  • 检查startpoint变量是否比当前时间早 30 秒。 因为每次运动检测都会重置这个变量,所以我们知道距离上次运动检测至少有 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")

您也可以为此使用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)时,您可能会遇到麻烦。 在这种情况下,您可能希望使用锁定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM