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

Uddy

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 :stuck_out_tongue: 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:

Wire.begin(addr_node1);
....
Wire.beginTransmission(addr_node2);
....

On node2:

Wire.begin(addr_node2);
...
Wire.beginTransmittion(addr_node1);

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();    
  Serial.println(x); 
}

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

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

I assume that you also setup the receiveEvent handler using

 Wire.onReceive(receiveEvent);

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

Yup, this is my setup function:

void setup()
{
  Wire.begin(ID);           
  Wire.onReceive(receiveEvent); 
   Wire.onRequest(requestEvent);
  Serial.begin(57600);   
  pinMode(13, OUTPUT);
}