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''

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值