python 只执行一次的语句_python - 在Python中的一段时间内只执行一次if语句? - SO中文参考 - www.soinside.com...

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

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

创建一个从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语句,计时器休眠,但这不起作用。有小费吗?谢谢。

python

arduino

2个回答

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只在可能的情况下发射。

干杯

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

热门问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值