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

Python smbus2用i2c_rdwr突破32字节限制失败求助

问题

树莓派3通过SMBus读取Arduino的50字节数据时,受SMBus单块数据≤32字节的限制影响,使用smbus2库的i2c_rdwr方法尝试一次性读取50字节,仅前32字节有效,后续18字节均为0xFF填充。

测试代码

from smbus2 import SMBus, i2c_msg

bus = SMBus(1)
read = i2c_msg.read(addr, 50)
bus.i2c_rdwr(read)
res = list(read)

print(''.join([chr(i) for i in res]))

运行结果

[32字符有效文本]+ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ
解决方法
  • 拆分读取任务:将50字节拆分为两次读取操作,先读取32字节,再读取剩余18字节,最后拼接结果:
    from smbus2 import SMBus, i2c_msg
    
    bus = SMBus(1)
    # 读取前32字节
    read_part1 = i2c_msg.read(addr, 32)
    bus.i2c_rdwr(read_part1)
    # 读取剩余18字节
    read_part2 = i2c_msg.read(addr, 18)
    bus.i2c_rdwr(read_part2)
    # 合并结果
    full_data = list(read_part1) + list(read_part2)
    print(''.join([chr(i) for i in full_data]))
    
  • 调整Arduino端的I2C缓冲区:Arduino默认Wire库的收发缓冲区大小为32字节,若要支持更大的单块传输,可修改Wire.h中的BUFFER_LENGTH宏(部分版本支持),或者在Arduino端实现分块发送逻辑,每次发送32字节,直到所有数据发送完毕。
  • 确认树莓派总线配置:检查树莓派/boot/config.txt中的I2C配置,确保dtparam=i2c_arm=on未添加SMBus相关限制参数,保证总线以原始I2C模式运行。

内容的提问来源于stack exchange,提问作者Rian Wardana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:01:21