在python中每次中断后重置睡眠时间

2024-06-01 01:00:00 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我在处理PIR传感器,当发现入侵者时需要1分钟的睡眠时间。当入侵者在睡眠时间被检测到时,我想重置这个睡眠时间。 代码如下:

`import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN)

try:
    while True:
        i=GPIO.input(18)
        if i==1:
            print("Intruder")
            time.sleep(60)
        elif i==0:
            print("No intruder")
            time.sleep(60)
except keyboardInterrupt:
    GPIO.cleanup()
    exit(0)`

Tags: 代码importgpiotimeas时间sleep传感器
2条回答

下面是一个使用线程的解决方案:

from threading import Thread, Event
import time

import RPi.GPIO as GPIO


class MyThread(Thread):
    def __init__(self, timeout=60):
        super(MyThread, self).__init__()
        self.intruder_spotted = Event()
        self.timeout = timeout

        self.daemon = True

    def run(self):
        while True:
            if self.intruder_spotted.wait(self.timeout):
                self.intruder_spotted.clear()
                print("Intruder")
            else:
                print("No intruder")



t = MyThread(60)

GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN)

try:
    t.start()
    while True:
        i=GPIO.input(18)
        if i==1:
            t.intruder_spotted.set()

        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()
    exit(0)

手上没有覆盆子馅饼。。。可以试试这个,用ipython的键盘输入。在

try:
    while True:
    # i=int(input('input number: '))
    i=int(i=GPIO.input(18))
        if i!=1:
            print("No intruder")
        else:
            print("Intruder")
        time.sleep(60)

相关问题 更多 >