Arduino与Python串口通信double类型数据转换问题求解
问题根因与解决方法
- 类型不匹配:你存储串口读取结果的
byte_groesse是由8个独立单字节对象组成的列表,struct.unpack要求输入连续的bytes类型数据,需要先完成列表到bytes的转换 - 格式符错误:Arduino发送的是8字节双精度浮点数(double),你之前用的
f格式符对应4字节单精度浮点数,需要改用d格式符,同时Arduino AVR架构默认使用小端序,格式符前加<前缀匹配字节序。
具体实现步骤
- 取消代码中
import struct的注释 - 使用
b''.join(byte_groesse)将字节列表拼接为完整的bytes对象 - 调用
struct.unpack('<d', 拼接后的bytes)完成解析,返回的元组第一个元素就是你需要的浮点数值
修改后的可运行代码
import serial import struct # 初始化存储8字节的列表 byte_groesse = [0]*8 ser = serial.Serial(port='COM8', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=1) ser.flushInput() try: while True: # 连续读取8个字节 for i in range(8): byte_groesse[i] = ser.read() # 拼接列表为bytes raw_bytes = b''.join(byte_groesse) # 解析为double value = struct.unpack('<d', raw_bytes)[0] print(f"解析得到的数值:{value}") except KeyboardInterrupt: ser.close() print("串口已关闭")
额外优化建议
你也可以直接调用ser.read(8)一次性读取8个字节,不需要循环逐个读,代码可以更简洁,还能避免列表操作的冗余逻辑:
while True: raw_bytes = ser.read(8) # 校验读取到的字节长度是否符合要求,避免串口丢包导致解析错误 if len(raw_bytes) == 8: value = struct.unpack('<d', raw_bytes)[0] print(f"解析得到的数值:{value}")
内容的提问来源于stack exchange,提问作者Wiesel97
相关产品推荐
相关产品推荐

