Python-传感器测量挂起

问题描述 投票:0回答:1

[我正在尝试编写一个程序,在感官传感器的滚动测量值达到特定值后,python代码在if语句上执行功能。

我有一个问题,即使传感器在睡眠计时器阈值之内又回到其原始位置之后,也会执行if语句。

输出:

enter image description here

代码:

while True:

    #checks for sensor status every 20 loop iterations (prevents too many web server requests)
    if(loopCount >= 40):
        loopCount = 0 #resets the loop counter
        sensorStatus = checkSensorStatus() #check the sensors status

    elif (sensorStatus == "on"):
        #orientation = sense.get_gyroscope()
        orientation = sense.get_orientation()

        roll=round(orientation["roll"], 0)
        time.sleep(0.1)

        print("\nRoll: ", roll)

        if roll >= 300 or roll <= 250:
            litterBoxUsed()
            print("Sensor paused for 10 seconds")
            time.sleep(10) #Sleeps for 10 seconds before starting to use sensor again
            print("Sensor active.")

    loopCount += 1

没有人知道如何防止此问题并且仅执行一次if语句吗?

根据要求输出定时数据:enter image description here

python raspberry-pi raspberry-pi3 sensor gyroscope
1个回答
0
投票

您需要跟踪的不仅是传感器的状态(角度),还包括activeinactive状态之间的转换,其中active表示roll is outside of idle range

is_activated = False

while True:

    if(loopCount >= 40):
        loopCount = 0 #resets the loop counter
        sensorStatus = checkSensorStatus() #check the sensors status
        is_activated = False

    elif (sensorStatus == "on"):
        #orientation = sense.get_gyroscope()
        orientation = sense.get_orientation()

        roll=round(orientation["roll"], 0)
        time.sleep(0.1)

        print("\nRoll: ", roll)

        if roll >= 300 or roll <= 250:
            if is_activated == False:
                is_activated = True
                litterBoxUsed()
                # [no longer required] print("Sensor paused for 10 seconds")
                # time.sleep(10) #Sleeps for 10 seconds before starting to use sensor again
                print("Sensor active.")
        else:
            is_activated = False

    loopCount += 1
© www.soinside.com 2019 - 2024. All rights reserved.