首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我在向代码中添加计时器时遇到问题

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

Stack Overflow用户
提问于 2020-04-12 18:00:36
回答 2查看 37关注 0票数 1

我正在从事这个项目与运动传感器,其中我希望有监视器关闭时,有没有运动后,一定的时间过去了。但每次有动作时,我都希望计时器重置。

我有打开和关闭监视器的代码,但是我如何添加计时器呢?

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

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

回答 2

Stack Overflow用户

发布于 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")

票数 0
EN

Stack Overflow用户

发布于 2020-04-12 18:49:48

您也可以使用threading来实现这一点。

代码语言:javascript
复制
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)时,您可能会遇到麻烦,因为它在另一个线程上执行回调。在这种情况下,您可能希望使用锁定。

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

https://stackoverflow.com/questions/61169664

复制
相关文章

相似问题

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