小弟最近在进行数据通信,板子通过FGPA发送2Mbit/s的连续8位2进制数,用光纤发送,通过转换板,用TTL转USB连接到电脑上,利用python的serial库进行接收,数据会存在丢包的现象,比如,两个小时下来,丢了十几次。有时候测试下来也会不丢,很奇怪。代码如下:
import threading import datetime import serial import queue import time import csv data_queue = queue.Queue() # 串口读取线程函数 def serial_read_thread(ser): while True: try: if ser.in_waiting>0: data = ser.read(ser.in_waiting) # 读取当前可用的所有数据 data_queue.put(data) # time.sleep(0.02) # 短暂休眠以减轻CPU压力并允许更多数据到达 except serial.SerialException as e: print(f"Serial error: {e}") break # 文件写入线程函数 def file_write_thread(): data_dec = [] data_dec1=[] while True: data = data_queue.get() for byte in data: decimal_value = int.from_bytes([byte], byteorder='big') data_dec.append(decimal_value) if len(data_dec)>4096: data_dec1=data_dec[:4096] data_dec= data_dec[4096:] timestamp = int(datetime.datetime.now().timestamp() * 1000) stamp = [timestamp for _ in range(512)] columns = [stamp] + [[] for _ in range(8)] # 先添加stamp,再添加8个空列表 # 使用循环将数分配到八个列表中(现在索引从1开始,因为0是stamp) for i, num in enumerate(data_dec1): column_index = (i % 8) + 1 # 加1是因为我们想要跳过索引0(stamp) columns[column_index].append(num) # 写入CSV文件 with open('output.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) for row in zip(*columns): writer.writerow(row) # 主程序 def main(): ser = serial.Serial( port='COM4', baudrate=2000000, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_TWO, parity=serial.PARITY_NONE, # rtscts=True, # timeout=0.02, ) ser.set_buffer_size(rx_size=200000) if not ser.is_open: ser.open() print("串口已打开") # 创建并启动串口读取线程xe read_thread = threading.Thread(target=serial_read_thread, args=(ser,), daemon=True) read_thread.start() # 创建并启动文件写入线程 write_thread = threading.Thread(target=file_write_thread, daemon=True) write_thread.start() # 主线程可以在这里做其他事情,或者等待线程结束 read_thread.join() write_thread.join() ser.close() # 关闭串口 if __name__ == "__main__": main()