最近向用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()