如何在 python 中暂停脚本以防止同时检测到 2 个传感器?

How do I pause a script in python to keep 2 sensors from being detected at same time?

我在检测 2 个振动传感器的 python 脚本中有这个功能,问题是传感器非常敏感,所以通常当一个被击中时,它们都会被检测到,这给我一个错误的读数。我将如何阻止它们同时被检测到?我想检测哪个是第一个。这是我试过的-

#!/usr/bin/env python
import RPi.GPIO as GPIO
from time import sleep

def setup():
    GPIO.setmode(GPIO.BOARD)         
    GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(ShockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

def shock():
    print('shock')

def knock():
    print('knock')

def register_callbacks():
    if GPIO.add_event_detect(ShockPin, GPIO.FALLING, callback=shock, bouncetime=5000):
        sleep(5)
    elif GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=knock, bouncetime=5000):
        sleep(5)

if __name__ == '__main__':
    try:
        setup()
        register_callbacks()

只是一个建议,我没有测试它的设置。保存最后一个事件的时间(使用datetime),然后检查最后一个事件是否超过5秒前。

import datetime
sensor_delay = 5 #delay in seconds
last_event = datetime.datetime.now()

def shock():
    global last_event
    if datetime.datetime.now() > last_event + datetime.timedelta(seconds=sensor_delay):
        print ('shock')
        last_event = datetime.datetime.now()

def knock():
    global last_event
    if datetime.datetime.now() > last_event + datetime.timedelta(seconds=sensor_delay):
        print('knock')
        last_event = datetime.datetime.now()