python获取串口数据_python 下串口数据的读取,解析,和保存-

#!/usr/bin/python#-*-coding: utf-8 -*-

importserialimportthreadingimportbinasciifrom datetime importdatetimeimportstructimportcsvclassSerialPort:def __init__(self, port, buand):

self.port=serial.Serial(port, buand)

self.port.close()if notself.port.isOpen():

self.port.open()defport_open(self):if notself.port.isOpen():

self.port.open()defport_close(self):

self.port.close()defsend_data(self):

self.port.write('')defread_data(self):globalis_exitglobaldata_byteswhile notis_exit:

count=self.port.inWaiting()if count >0:

rec_str=self.port.read(count)

data_bytes=data_bytes+rec_str#print('当前数据接收总字节数:'+str(len(data_bytes))+' 本次接收字节数:'+str(len(rec_str)))

#print(str(datetime.now()),':',binascii.b2a_hex(rec_str))

serialPort= 'COM6' #串口

baudRate = 115200 #波特率

is_exit=False

data_bytes=bytearray()if __name__ == '__main__':#打开串口

mSerial =SerialPort(serialPort, baudRate)#文件写入操作

filename=input('请输入文件名:比如test.csv:')

dt=datetime.now()

nowtime_str=dt.strftime('%y-%m-%d %I-%M-%S') #时间

filename=nowtime_str+'_'+filename

out=open(filename,'a+')

csv_writer=csv.writer(out)#开始数据读取线程

t1 = threading.Thread(target=mSerial.read_data)

t1.setDaemon(True)

t1.start()while notis_exit:#主线程:对读取的串口数据进行处理

data_len=len(data_bytes)

i=0while(i

frame_code=data_bytes[i+2]

frame_len=struct.unpack('

frame_time=struct.unpack('

if frame_code==0x03: #判断帧类型

#struct 解析数据帧

accelerated_x,accelerated_y,accelerated_z,angular_x,angular_y,angular_z,tem,speed_x,speed_y,speed_z,\

angular_v_x,angular_v_y,angular_v_z=struct.unpack('

dt=datetime.now()

nowtime_str=dt.strftime('%y-%m-%d %I:%M:%S') #时间

loc_str=[nowtime_str,frame_time,accelerated_x,accelerated_y,accelerated_z,angular_x,angular_y,angular_z,tem,speed_x,speed_y,speed_z,\

angular_v_x,angular_v_y,angular_v_z]#写入csv文件

try:

csv_writer.writerow(loc_str)exceptException as e:raisee

i=i+6+frame_len+3

else:

i=i+1data_bytes[0:i]=b''

你可能感兴趣的:(python获取串口数据)