You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过HC-05传输MPU6050数据时Python接收出现分块乱序问题

解决蓝牙接收IMU数据分块乱序的问题

问题原因

蓝牙串口属于流传输,sock.recv(size)会返回当前缓冲区中任意长度的数据——可能是半行、一整行甚至多行。直接打印这些数据就会出现分块、乱序的情况,而Arduino端用Serial1.println发送数据时,每行末尾会自动添加\r\n换行符,这是识别完整行的关键标记。

修改后的Python接收代码

import bluetooth 

target_name = "HC-05"
target_address = None
        
nearby_devices = bluetooth.discover_devices()
        
for bdaddr in nearby_devices:
    if target_name == bluetooth.lookup_name(bdaddr):
        target_address = bdaddr
        break
if target_address is not None:
    print ("found target bluetooth device with address ", target_address)
else:
    print ("could not find target bluetooth device nearby")

port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
size = 512
sock.connect((target_address, port))
print("CONNECTED")

# 定义缓冲区,累积不完整的行数据
buffer = ""
while True:
    data = sock.recv(size)
    data = data.decode('ascii')
    # 将新接收的数据追加到缓冲区
    buffer += data
    # 按换行符分割,分离完整行与剩余不完整数据
    lines = buffer.split('\n')
    # 更新缓冲区为最后一段不完整内容(可能为空)
    buffer = lines[-1]
    # 遍历处理所有完整的行
    for line in lines[:-1]:
        # 清除回车符与多余空格,还原单行格式
        clean_line = line.strip('\r').strip()
        print(clean_line)
        # 如需解析数据,可在此处拆分
        # imu = clean_line.split(',')
        # if len(imu) ==3:
        #     yaw, pitch, roll = map(float, imu)
        #     print(f"Yaw: {yaw}, Pitch: {pitch}, Roll: {roll}")

关键修改点

  • 新增buffer变量累积接收数据,避免丢失半行内容
  • 通过split('\n')拆分缓冲区,分离完整行与剩余不完整数据
  • 仅处理完整行,保证输出与Arduino串口监视器一致的单行格式
  • 用strip('\r')清除Arduino发送的回车符,避免控制字符干扰输出

内容的提问来源于stack exchange,提问作者Ashfaque Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:30:48