Raspberry Pi 作为 I2C 中的 Slave 和 arduino 作为 Master

Abh*_*iya 5 arduino i2c raspberry-pi

我正在尝试编写一个代码,在其中我在 arduino 中运行我的主程序,并在需要时从树莓派的 i2c 总线获取数据。因此,我需要将我的 arduino 配置为 I2C Master,将 raspberry pi 配置为 I2C slave。是否有可能以与使 pi 为主而 arduino 为从属相同的方式来做到这一点?如果没有,还有其他可能的方法吗?

PS:-我只做一对一的通信,即arduino为主,树莓为从。没有连接其他设备。

谢谢你的帮助。

Gus*_*ler 0

是的; 这是我在构建气象站时所做的事情,我需要 Arduino 模拟和中断触发输入。在 Master 上,Python 代码将类似于:

i2c_ch = 1
bus = smbus.SMBus(i2c_ch)
#address of the Arduino slave:
i2c_address = 20 
...
readArray  = bus.read_i2c_block_data(i2c_address,8)

Run Code Online (Sandbox Code Playgroud)

然后在 Arduino 上,代码将如下所示:

#define I2C_SLAVE_ADDR 20

void setup() {
  Wire.begin(I2C_SLAVE_ADDR);
  Wire.onReceive(receieveEvent); 
  Wire.onRequest(requestEvent);
}

void receieveEvent() { //for reading data from the master
  byte byteRead = 0;
  while(0 < Wire.available()) // loop through all but the last
  {
    byteRead = Wire.read();
  }
}

void requestEvent(){ //for sending data to the master
  long val = millis(); //whatever you want to send, in this case millis()
  byte buffer[4];
  buffer[0] = val >> 24;
  buffer[1] = val >> 16;
  buffer[2] = val >> 8;
  buffer[3] = val;
  Wire.write(buffer, 4);
}
Run Code Online (Sandbox Code Playgroud)

有关此内容的更多详细信息,请查看我为此气象站代码制作的 github 存储库: https: //github.com/judasgutenberg/i2c-weather-slave