I2C 2ways communication between 2 uno's

Hi,
I want to communicate from one arduino to an other via I2C, but also from the second back to the first one. also I have connected 2 I2C modules on the bus.
I receive data from those 2 modules and can send data to the other uno board but I want get some information back.
I tried onReceive() and onRequest() those 2 works seperatly but not together.
I don't know why?

I guess it will if the 2 uno's are 2 masters? but I don't know how to program that.

ps: looked already on the internet but never had a good example.

If anyone knows please let me know.

Thanks.

You can have two Masters.

You program each controller as a master. You also give each one a different I2C slave address, and add the slave routines for processing incoming messages. Then each controller can send a message to the slave address of the other one.

Be prepared for collissions, when both masters try to use the bus at the same time. I.e. you check the result of the transmit functions and retry later if something went wrong.

okeey it can communicate both ways :slight_smile:
but how do you code 1uno as a master AND as a slave ?

can you give me some code examples.

Im new to programming, firt steps :confused:

Merge the master and slave_receiver examples. In the receiveEvent() you store the received message for use in loop().

I tried onReceive() and onRequest() those 2 works seperatly but not together.
I don't know why?

The slave should be able to have both of these in the same sketch. Its very common to receive a command from a master with an onReceive, perform some actions dependent upon that command, and then send data back with an onRequest routine() in response to a wire.requestFrom() by the master.

Please post the code which did not work correctly.

Also it will help clarify matters if you can attach a sketch of your architecture and explain the reason why you think an Arduino needs to be a slave or a master or both.

Arduino #1

const byte MY_ADDRESS = 25;
const byte SLAVE_ADDRESS = 42;

void setup() 
  {
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);
  }

Arduino #2

const byte MY_ADDRESS = 42;
const byte OTHER_ADDRESS = 25;

void setup () 
  {
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);
  }