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

树莓派4无法读取Arduino Uno的I2C数据(缓冲区为空)

解决Arduino Uno与树莓派4 I2C通信读取失败问题

核心问题:Arduino端I2C角色配置错误

你的Arduino代码错误地将自身当作I2C主机主动发送数据,但实际树莓派是I2C主机,Arduino需要作为从机,等待主机发起读取请求后再响应发送数据——这是通信失败的根本原因。

修正后的Arduino代码

将Arduino配置为I2C从机,注册读取回调函数,当树莓派发起读取操作时自动发送数据:

#include <Wire.h>

byte val = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("Starting I2C slave at address 0x08");
  Wire.begin(0x08); // 初始化Arduino为I2C从机,地址设为0x08
  Wire.onRequest(sendData); // 注册主机读取时的回调函数
}

// 主机发起读取时触发此函数,发送数据
void sendData() {
  Wire.write(val++);
  Serial.print("sent: "); Serial.println(val-1);
  Wire.write(val++);
  Serial.print("sent: "); Serial.println(val-1);
  Wire.write(val++);
  Serial.print("sent: "); Serial.println(val-1);
}

void loop() {
  delay(500); // 循环延迟不影响I2C回调逻辑
}

修正后的树莓派C++代码

原代码存在两个关键问题:一是尝试读取24字节但从机每次仅发送3字节,二是用strlen处理二进制数据(可能包含0值导致截断)。以下是修正版本:

#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    int file_i2c;
    const int read_len = 3; // 与从机发送的字节数保持一致
    unsigned char buffer[60] = {0};

    char *filename = (char*) "/dev/i2c-1";
    cout << "Starting I2C read program" << endl;

    if ((file_i2c = open(filename, O_RDWR)) < 0) {
        cerr << "Failed to open I2C bus" << endl;
        return -1;
    }

    int addr = 0x08;
    if (ioctl(file_i2c, I2C_SLAVE, addr) < 0) {
        cerr << "Failed to access slave device" << endl;
        return -1;
    }

    while (true) {
        ssize_t bytes_read = read(file_i2c, buffer, read_len);
        if (bytes_read != read_len) {
            cerr << "Failed to read from I2C bus, received " << bytes_read << " bytes" << endl;
        } else {
            cout << "Data read: ";
            for (int i = 0; i < read_len; i++) {
                printf("%02X ", buffer[i]); // 以十六进制格式打印每个字节
            }
            cout << endl;
        }
        sleep(1); // 匹配从机发送频率,避免频繁读取
    }

    close(file_i2c);
    return 0;
}

额外检查事项

  • 接线确认:Arduino的SDA接树莓派GPIO2(SDA1),SCL接GPIO3(SCL1),必须将两者的GND引脚相连共地。
  • 树莓派I2C启用:通过raspi-config进入"Interface Options"启用I2C接口,重启后生效。
  • 权限问题:运行树莓派程序时需添加sudo,或执行sudo usermod -aG i2c pi将当前用户加入i2c组(重启后生效)。
  • 工具替代:无需使用已废弃的WiringPi,Linux原生I2C设备接口即可满足需求,你的代码方向是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 06:17:30