two way serial communication using Wire library

Hi there, I'm trying to interface an Arduino with a Lego Mindstorms NXT using I2C, essentially with the Arduino as a smart sensor. I am using the Wire library on the Arduino to handle this. It works great, but when I use both receiveEvent() and requestEvent() in one program, such as when I want the NXT to specify what information it wants to read, no matter what message the Arduino receives, receiveEvent() is called, and the requestEvent() is ignored. Is it possible to do use both functions in one program? Would I need to edit the Wire files?

Thanks in advance for any help, I can provide code sample if needed


The short answer is a definitive yes. You will need to assign an address to the master during your setup routine (so both master and slave would be addressable). This address needs to be different from that of the slave's.

Sorry for the delay in replying, I gave up on this project :P but decided to give it another go. What do you mean assign an address to the master? And what function would I then use to send messages to the master when it requested information? Thanks again

Wire.begin takes an address as optional parameter. When you want to perform bi-directional communication, for each of the device, Wire.begin must take a different address.

So the code looks something like this:

On node1:


On node2:


Let me know if it makes sense.

For actually sending the data from the slave arduino to the master (which is not an arduino), i'm using the wire.send function which works fine, my problem is that when my master requests data from the arduino, the requestEvent function will only be called if there is no receiveEvent function, in which case it works perfectly

So in this case:

void receiveEvent(int howMany)
  int x = Wire.receive();    

void requestEvent() {
  byte outbuf[3] = {1,2,3};

no matter what message the arduino recieves, requestEvent is never called, only receive event

I assume that you also setup the receiveEvent handler using


If it is not setup, the receiveEvent function will not get called automatically.

Yup, this is my setup function:

void setup()
  pinMode(13, OUTPUT);