我正在做一个智能自行车背光与覆盆子Pi和一个SenseHat在上面。
我在测量SenseHat加速度计的输出值。实际上有三个值被报告为x,y,z,我想知道的是,我的自行车是否静止了15秒或更长时间。因此,如果这些值一直保持不变超过15秒,我将关闭背光。然后,如果他们开始改变,并保持这样超过15秒,我希望它参与,并开始运作。
到目前为止,我已经实现了频闪效应,即当自行车处于空闲状态时自动激活。一个转向检测-我显示箭头动画的左和右基础上的目标检测传感器,我放置在车把附近。我还实现了刹车检测。一旦加速度计检测到刹车,我就会显示出全红灯。
如果您检查代码,您会发现它有点棘手,因为整个过程都在while循环中,我需要将这个检测作为一个If条件,然后在下面添加其他条件,将我现有的if条件放在那里(例如,去加速或转弯检测)。
那么,如何使在不使用time.delay的情况下测量特定值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, y, 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发布于 2020-08-15 17:12:57
其基本思想是跟踪上次检测到运动(或非运动)的时间。如果是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()发布于 2020-08-15 17:14:31
有一些较小的事情需要首先解决:
input = ser.read()。input实际上是一个内建,不应该用作变量名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, y, 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)https://stackoverflow.com/questions/63428511
复制相似问题