维特智能老总给我写的代码,分享给大家,写的超级好
# -*- 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*16 ay = sData[1]/32768*16 az = sData[2]/32768*16 print("acc:%fg,%fg,%fg"%(ax, ay, az)) elif data[1] == 0x52: gx = sData[0]/32768*2000 gy = sData[1]/32768*2000 gz = sData[2]/32768*2000 print("gyro:%.1f°/s,%.1f°/s,%.1f°/s"%(gx, gy, gz)) elif data[1] == 0x53: roll = sData[0]/32768*180 pitch = sData[1]/32768*180 yaw = sData[2]/32768*180 print("angle:%.1f°,%.1f°,%.1f°"%(roll, pitch, yaw)) def readData(): # 检查串口是否打开 if ser.isOpen(): print("串口已打开") witpack = bytearray(11) index = 0 try: # 默认串口是休眠状态,先发一串字符唤醒串口功能再发指令 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") # 5Hz ser.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") # 100Hz time.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] = val index = index + 1 # 每包数量11个字节 if index >= 11: sumcheck = 0 for i in range(10): sumcheck = sumcheck + witpack[i] sumcheck = sumcheck & 0xff if witpack[0] == 0x55 and sumcheck == witpack[10] : # print("校验成功", witpack[1]) index = 0 analysWitData(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()
############################
QQ 3087438119