5
votes

I am trying to make write a code where i run my main program in arduino and take data from i2c bus from raspberry pi when required. Thus i need to configure my arduino as I2C Master and raspberry pi as I2C slave. Is it possible to do it in the same way as making pi the master and arduino the slave? If not, is any other way possible?

P.S.:- I am doing only one-one communication that is arduino as master and raspberry as slave. There are no other devices connected.

Thanks for your help.

1
I was searching for PI as I2C slave too and probably the following link ist the answer we don't want: raspberrypi.stackexchange.com/questions/5584/…user3466446

1 Answers

0
votes

Yes; this is something I did when building a weather station where I needed Arduino analog and interrupt-triggering inputs. On the Master the python code will look something like:

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)

Then on the Arduino the code will look like:

#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);
}

For more details on this, check out the github repo I made for this weather station's code here: https://github.com/judasgutenberg/i2c-weather-slave