[英]Execute if statement only once in a period of time in Python?
創建一個從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()函數,此后,僅當值降至50以下且THEN> 50再次時,if語句才不再觸發。 我嘗試使用True / False語句,但計時器卻睡着了,但這沒有用。 有小費嗎? 謝謝。
您只需要添加更多邏輯條件即可控制程序的流程。 這樣的事情會起作用:
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
僅在可能的if
下)觸發。
干杯
您只需跟蹤要實現目標的所需內容:上次警告的時間戳以及距離是否低於您要跟蹤的值。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.