在Python中的一段时间内只执行一次if语句?

时间:2017-12-26 17:17:03

标签: python arduino

创建一个从arduino距离传感器接收数据的python脚本。我每纳秒收到一个值。每当此值高于50时,我想警告用户。 (最终会通过通知程序执行此操作,但现在我只是打印警告)。我有以下内容:

while 1:                                                   # Keep receiving data
    data = ser.readline()                                  # Getting data from arduino
    value = [int(s) for s in data.split() if s.isdigit()]  # Converting the Arduino ouput to only get  the integer value
    if value:                                              # Avoid empty values
        distance = value[0]                                # List to int
            if distance > 50:                              # If bigger than 50 cm, warn user.
                warn_user()                 

我只想在30秒内执行一次warn_user()函数,之后,if语句不应再触发,只有当值低于50且THEN>时才会触发。再次50。我尝试使用True / False语句,计时器休眠,但这不起作用。有小费吗?感谢。

2 个答案:

答案 0 :(得分:2)

您只需添加一些更合理的条件来控制程序的流程。像这样的东西会起作用:

from time import time
warning_enabled = True
time_of_warning = 0

while 1:
    data = ser.readline()
    value = [int(s) for s in data.split() if s.isdigit()]
    if value:
        distance = value[0]
            if distance > 50 and warning_enabled:
                warn_user()
                warning_enabled = False
                time_of_warning = time()
            if time() - time_of_warning > 30 and not warning_enabled and distance < 50:
                warning_enabled = True

这样做是因为它会跟踪上次触发警告的时间,并使用warning_enable标记使第二个if仅在可能的情况下触发。

干杯

答案 1 :(得分:2)

您只需跟踪您要实现目标的内容:上次警告的时间戳以及距离是否低于您正在跟踪的值。

import time

distance_was_safe = True  # tracks if distance went below specified range
last_warned = 0           # tracks timestamp since last warning

safe_distance = 50  # 50 cm
warn_interval = 30  # 30 sec, warn no more than once every interval


while True:
    # Get data from Arduino.
    data = ser.readline()                                  

    # Convert the Arduino output to only get the integer values.
    value = [int(s) for s in data.split() if s.isdigit()]

    # Avoid empty output.
    if value:                                              
        # Get the first integer.
        distance = value[0]

            # If greater than safe zone, potentially warn the user.
            if distance > safe_distance:

                # Warn the user if distance was below range,
                # and it has been enough time since the last warning.
                if distance_was_safe and time.time() - last_warned > warn_interval:
                    distance_was_safe = False
                    last_warned = time.time()
                    warn_user()

            else:
                # Distance was less than warning distance, reset the flag.
                distance_was_safe = True