树莓派作为I2C从设备,Arduino作为主设备

6
我正在尝试编写一段代码,其中我在Arduino上运行我的主程序,并在需要时从树莓派的I2C总线中获取数据。因此,我需要将我的Arduino配置为I2C主机,将树莓派配置为I2C从机。是否可以以与使树莓派成为主机、Arduino成为从机相同的方式进行操作?如果不行,是否有其他方法可行?
附言:我只进行一对一通信,即Arduino作为主机,树莓派作为从机。没有其他设备连接。
感谢您的帮助。

1
我也在寻找将树莓派作为I2C从设备的方法,但可能以下链接并不是我们想要的答案:http://raspberrypi.stackexchange.com/questions/5584/i2c-raspberri-pi-as-a-slave - user3466446
1个回答

0

是的,这是我在构建一个天气站时所做的事情,我需要Arduino模拟和中断触发输入。在主控端,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)

然后在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);
}

如需更多详细信息,请查看我为该天气站代码创建的 GitHub 存储库:https://github.com/judasgutenberg/i2c-weather-slave


1
OP希望树莓派成为从设备,而Arduino成为主设备。但是你的代码使树莓派成为主设备,Arduino成为从设备。 - Arrow_Raider

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接