先进行串口初始化
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)
也可以用添加列表的方式加标题
writer.writerow(['序号','数据1','数据2'])