如何解决如何衡量一个值在一段时间内保持不变?
我正在使用Raspberry Pi和顶部的SenseHat制作智能自行车背光。
我正在测量SenseHat加速度计的输出值。实际上,有三个值报告为x,y,z,而我想知道的是我的自行车是否静止了15秒或更长时间。因此,如果这些值在15秒钟内保持不变,我将关闭背光灯。然后,如果他们开始改变并像这样保持15秒钟以上,我希望它参与并重新开始运行。
到目前为止,我已经实现了频闪效果,当自行车闲置时会自动激活。转向检测-根据放置在车把附近的物体检测传感器,向左和向右显示箭头动画。我还实现了刹车检测。一旦加速度计检测到制动,我就会显示全红灯。
如果您检查代码,您会发现它有点棘手,因为整个过程都在while循环中,因此我需要将此检测作为if条件,然后在下面添加else,将现有的if条件放在其中(例如减速或转弯检测)
那么我如何不使用time.delay使Python在15秒钟内测量某些值,并根据它们是否更改或保持不变来做事?
while True:
ser.flushInput()
ser.flushOutput()
x,y,z = sense.get_accelerometer_raw().values()
x = round(x,2)
y = round(y,2)
z = round(z,2)
print("x=%s,y=%s,z=%s" % (x,z))
input = ser.read() #serial input i'm getting from arduino,it tells me if my left or right steering sensors are triggerred.
yon = input.decode("utf-8")
int(yon)
if (z > 0.20): #If deacceleration is detected
fren() # brake function is called
else: # if no breaking is detected...
if (yon == "1"): #if left turn sensor triggered
sag_ok() #show left turn animation on led matrix
elif (yon =="2"): # if right turn sensor triggered
sol_ok() #show right turn animation on led matrix
else: #anything else
strobe() #show strobe effect if nothing else is detected
解决方法
基本思想是跟踪上一次检测到运动(或不运动)的时间。如果已超过15秒,请关闭(打开)灯光。
类似这样的东西:
from time import monotonic
TAIL_LIGHT_DELAY = 15
time_of_last_motion = monotinic()
time_of_last_stop = monotonic()
while True:
now = monotonic()
motion = (abs(x) > 0.2) or (abs(y) > 0.2) or (abs(z) > 0.2)
if motion:
time_of_last_motion = now
if now - time_of_last_stop > TAIL_LIGHT_DELAY:
turn_on_tail_light()
else:
time_of_last_stop = now
if now - time_of_last_motion > TAIL_LIGHT_DELAY:
turn_off_tail_light()
,
首先需要解决许多较小的问题:
-
input = ser.read()
。input
实际上是builtin,不应用作变量名 -
int(yon)
不执行任何操作。您可以将其转换为int
,但由于未将结果分配回名称而导致结果丢失 -
if (z > 0.20)
和所有其他if
检查-括号在这里实际上不起作用;您可以放下它们。
一个更大的问题要解决:绝对没有理由,该循环在CPU内核上全负荷运行。每秒几千次,不断。您应该引入time.sleep
来减少负载。
鉴于此,您可以结合使用布尔值标志和加速度计最后一次给出0值的记录来实现所需的输出。
import time
import datetime as dt
last_zeros = None
countdown_started = False
while True:
ser.flushInput()
ser.flushOutput()
x,y,z = sense.get_accelerometer_raw().values()
x = round(x,2)
y = round(y,2)
z = round(z,2)
print("x=%s,y=%s,z=%s" % (x,z))
if x == 0 and y == 0 and z == 0:
if countdown_started:
duration = (dt.datetime.utcnow() - last_zeros_time).total_seconds()
if duration > 15:
# Do something to turn the light off here
continue
else:
countdown_started = True
last_zeros_time = dt.datetime.utcnow()
else:
countdown_started = False
sensor_input = ser.read()
yon = sensor_input.decode("utf-8")
if (z > 0.20):
fren()
else:
if (yon == "1"):
sag_ok()
elif (yon =="2"):
sol_ok()
else:
strobe()
time.sleep(0.5)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。