Python读取串口数据并创建csv文件

先进行串口初始化

comList = list(serial.tools.list_ports.comports())
len = len(comList)
i = 0
while i < len:
    comAttr = list(comList[i])
    print(comAttr[0])
    i = i+1
    
serialport = serial.Serial()
serialport.port = comAttr[0] #串口号,也可以手动输入
serialport.baudrate = 115200 #波特率
serialport.bytesize = 8
serialport.parity = serial.PARITY_NONE
serialport.stopbits = 1
serialport.timeout = 1
serialport.close()

if not serialport.is_open:
    serialport.open()
time.sleep(0.001) #时间设置参考串口传输速率

创建文件,第一列为序号n,第二列为数据

with open('result.csv','w',encoding='utf8',newline='') as f :
    n = 0
    ls = []
    data = []
    writer = csv.writer(f)
    while True:
        n += 1
        data = serialport.readline()
        ls.clear()
        ls.append(n)
        ls.append(data)
        writer.writerow(ls)

如果要插入多行数据

with open('result.csv','w',encoding='utf8',newline='') as f :
    n = 0
    ls = []
    data = [1,2]
    writer = csv.writer(f)
    while True:
        n += 1
        #data = serialport.readline()
        ls.clear()
        ls.append(n)
        for j in range(0,2):
            ls.append(data[j])
        writer.writerow(ls)

Python读取串口数据并创建csv文件_第1张图片
用excel打开生成的csv文件,方便进行拟合操作

也可以用添加列表的方式加标题

    writer.writerow(['序号','数据1','数据2'])

你可能感兴趣的:(python,python,开发语言)