# -*- coding: utf8 -*-import serial import time import datetime import struct# 替换成你的串口名称和波特率 ser = serial.Serial('COM5', 115200, timeout=1) def analysWitData(data):sData = struct.unpack("<hhhh", data[2:10])if data[1] == 0x50:print("time:%02d-%02d-%02d %02d:%02d:%02d.%03d"%(data[2], data[3], data[4], data[5], data[6], data[7], data[8]+data[9]*256))elif data[1] == 0x51:ax = sData[0]/32768*16ay = sData[1]/32768*16az = sData[2]/32768*16print("acc:%fg,%fg,%fg"%(ax, ay, az))elif data[1] == 0x52:gx = sData[0]/32768*2000gy = sData[1]/32768*2000gz = sData[2]/32768*2000print("gyro:%.1f°/s,%.1f°/s,%.1f°/s"%(gx, gy, gz))elif data[1] == 0x53:roll = sData[0]/32768*180pitch = sData[1]/32768*180yaw = sData[2]/32768*180print("angle:%.1f°,%.1f°,%.1f°"%(roll, pitch, yaw))def readData():# 检查串口是否打开if ser.isOpen():print("串口已打开")witpack = bytearray(11)index = 0try:# 默认串口是休眠状态,先发一串字符唤醒串口功能再发指令ser.write(b"WTZNWTZNWTZNWTZNWTZNWTZN")time.sleep(0.5)# 直接发送指令设置回传速率,该指令仅当前有效果,断电不保存# ser.write(b"\xff\xaa\x03\x03\x00") # 1Hz# ser.write(b"\xff\xaa\x03\x04\x00") # 2Hz# ser.write(b"\xff\xaa\x03\x05\x00") # 5Hzser.write(b"\xff\xaa\x03\x06\x00") # 10Hz# ser.write(b"\xff\xaa\x03\x07\x00") # 20Hz# ser.write(b"\xff\xaa\x03\x08\x00") # 50Hz# ser.write(b"\xff\xaa\x03\x09\x00") # 100Hztime.sleep(0.1)while True:if ser.in_waiting > 0:# 读取数据data = ser.read(ser.in_waiting)# 将数据转换为十六进制格式并打印print("接收到数据的十六进制表示:", data.hex())for val in data:witpack[index] = valindex = index + 1# 每包数量11个字节if index >= 11:sumcheck = 0for i in range(10): sumcheck = sumcheck + witpack[i]sumcheck = sumcheck & 0xffif witpack[0] == 0x55 and sumcheck == witpack[10] :# print("校验成功", witpack[1])index = 0analysWitData(witpack)else:for i in range(10): witpack[i] = witpack[i+1]index = index - 1# analysisHex(hex_data)time.sleep(0.1) # 稍作延时,避免过快的循环except KeyboardInterrupt:print("程序被用户中断")finally:ser.close()print("串口已关闭")# readData()
############################