我编写了一个python程序,以在Raspberry Pi 3B +上连续执行以下操作:
该程序通常会执行我想要的操作,但是当我检查.txt文件中的结果时,某些结果是“不可能的”,并指示我没有正确读取/转换串行数据。该传感器还以每秒100电报的速度输出数据,这远不及Raspberry Pi保存结果的实际速率(约2次测量/秒)。
我尝试编写一个仅读取串行数据,而没有其他内容的程序,并且能够跟上传感器的速度。我还尝试用ser.read_until()替换对标头的检查(在每个电报的末尾保留无用的标头)。但是,这导致电报的长度不同,这使得对6个变量的解析更加困难。 我现在(下面)使用的代码以分段方式(2、2、1、1、2、2、1个字节)读取电报,但有时返回的值似乎被误解了。
while 1:
now = datetime.now()
time_exact = now.strftime(str(now)[11:23])
date_time = now.strftime("%d-%m-%Y %H:%M")
data_dir = now.strftime("%d-%m-%Y")
save_path = "/home/pi/serial/"+data_dir+"/"
completename = os.path.join(save_path, date_time+".txt")
namepic = str(time_exact+".jpg")
completenamepic = os.path.join(save_path, data_dir+" "+time_exact+".jpg")
test = os.path.isdir(save_path)
if test == False:
os.mkdir(save_path)
subprocess.call(['chmod', '-R', '777', '/home/pi/serial'])
pass
else:
pass
x = ser.read(3)
if x != b'~~~':
print("Header mismatched")
x = ser.read(9)
d = 0
j = 0
elif x == b'~~~':
print("Serial communication started...")
y = ser.read(2)
a = ser.read(2)
c = ser.read(1)
e = ser.read(2)
g = ser.read(2)
i = ser.read(1)
z = int.from_bytes(y, byteorder='little', signed=False)/100
b = round(int.from_bytes(a, byteorder='little', signed=True)*0.0367, 2)
d = int.from_bytes(c, byteorder='little', signed=False)
f = int.from_bytes(e, byteorder='little', signed=False)/100
h = round(int.from_bytes(g, byteorder='little', signed=True)*0.0367, 2)
j = int.from_bytes(i, byteorder='little', signed=False)
if d >= signaltrigger:
signaltriggerA = 1
else:
signaltriggerA = 0
if j >= signaltrigger:
signaltriggerB = 1
else:
signaltriggerB = 0
if signaltriggerA or signaltriggerB or GPIO.input(trigger):
cam.capture(completenamepic)
M = open(completename,"a+",encoding='utf-8')
M.write('[%s]: Distance(a) = %s [m], Velocity(a) = %s [km/h], Signal(a) = %s [dB], Distance(r) = %s [m], Velocity(r) = %s [km/h], Signal(r) = %s [dB]. Trigger(a) = %s, Trigger(r) = %s, Trigger(ETZ) = %s. Picture: %s\n'%(time_exact,z,b,d,f,h,j,signaltriggerA,signaltriggerB,GPIO.input(trigger),namepic))
M.close()
pass
else:
print("No triggers detected")
我希望程序将每个传入的电报解析为6个片段,并将这些片段转换为结果(整数或浮点数),但有时这些结果的值会变得过高(对于传感器而言是不可能的)。我希望这是由手动读取不同的字节引起的(由于传感器不断吐出数据,因此花费了太多时间并丢失了电报的某些部分)。
如何确保正确读取和转换串行数据?另外,如果传感器以每秒100封电报的速度输出数据,但相机无法保持每秒100张图片的速度,那么是否可以计算移动平均值而不是仅使用许多电报中的一种?
答案 0 :(得分:0)
我将使用read_until()
来读取三个标头字节,并使用一些更简洁,更易读的方式将数据字节转换为值。
#!/usr/bin/env python3
from ctypes import LittleEndianStructure, c_int16, c_uint16, c_uint8, sizeof
from datetime import datetime
import os
class SensorData(LittleEndianStructure):
_pack_ = 1
_fields_ = [
('_distance', c_uint16),
('_velocity', c_int16),
('signal_strength', c_uint8),
]
@property
def distance(self):
return self._distance / 100
@property
def velocity(self):
return self._velocity * 0.0367
def to_string(self, name):
return (
f'Distance({name}) = {self.distance} [m],'
f' Velocity({name}) = {self.velocity} [km/h],'
f' Signal({name}) = {self.signal_strength} [dB]'
)
class Message(LittleEndianStructure):
_pack_ = 1
_fields_ = [
('sensor_a', SensorData),
('sensor_b', SensorData),
]
def main():
# ...
while True:
now = datetime.now()
save_path = f'/home/pi/serial/{now:%d-%m-%Y}'
log_path = os.path.join(save_path, f'{now:%d-%m-%Y %H:%M}.txt')
picture_filename = f'{now:%H:%M:%S.%f}.jpg'
picture_path = os.path.join(save_path, picture_filename)
os.makedirs(save_path, exist_ok=True)
ser.read_until(b'~~~')
message = Message.from_buffer_copy(ser.read(sizeof(Message)))
signal_trigger_a = message.sensor_a.signal_strength >= signal_trigger
signal_trigger_b = message.sensor_b.signal_strength >= signal_trigger
gpio_trigger = GPIO.input(trigger)
if signal_trigger_a or signal_trigger_b or gpio_trigger:
cam.capture(picture_path)
with open(log_path, 'a', encoding='utf-8') as log_file:
log_file.write(
f'[{now}]:'
f' {message.sensor_a.to_string("a")},'
f' {message.sensor_a.to_string("r")}.'
f' Trigger(a) = {signal_trigger_a},'
f' Trigger(r) = {signal_trigger_b},'
f' Trigger(ETZ) = {gpio_trigger}.'
f' Picture: {picture_filename}\n'
)
else:
print('No triggers detected')
if __name__ == '__main__':
main()