最近向用python写一个通过串口接收单片机输出数据流的程序,写了个大概,但是连接到实际串口中的时候,会出现两个问题。
1、只有压力传感器变化时才输出数据,我希望的是程序运行后,就像串口助手一样实时的传出数据,无论传感器是否有压力变化。
2、即使是有压力变化输出了数据帧,帧中的数据总是不满足按照规定字符的个数,有时候多有时候少。
请指点一下
import serial
import threading
# from Data_stitch import read_frames_from_txt
# 数据保存为txt
port1_txt_path = "F:/port11_data.txt"
port2_txt_path = "F:/port12_data.txt"
# 串口数据接收线程
def serial_thread(port, baudrate, bytesize, parity, stopbits, port_txt_path):
ser = serial.Serial(port, baudrate, bytesize, parity, stopbits)
if ser.is_open:
print('串口已打开')
with open(port_txt_path, 'w') as file:
if ser.in_waiting:
while True:
try:
data = ser.readline().strip()
file.write(data.hex())
print(data.hex())
except UnicodeDecodeError as e:
print('解码错误:', e)
continue
ser.close()
if not ser.is_open:
print('串口已关闭')
# 创建线程并启动
thread1 = threading.Thread(target=serial_thread('com9', 460800, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, port1_txt_path))
thread2 = threading.Thread(target=serial_thread('com10', 460800, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, port2_txt_path))
thread1.start()
thread2.start()
第一点,输出信息的是单片机,python只是接收,没法决定让对方怎么发吧,除非单片机能通过串口接收命令后改变发送频率。
第二点,可能是接收程序漏掉了什么,但也可能是单片机确实就发送有误,这个最好先想办法确认一下到底是哪边出问题了。我估计和你的读法有关 readline().strip(),这里显然可能会删掉某些字符。
是不是单片机不是实时发送的,用了中断还是单纯循环,如果单片机没问题那就是python接收解析问题了,字符有多有少可能是波特率问题,可以先试试单片机一直发送连续增加的数字看看有没有丢数,其实最好加点帧标志位