Using i2c with two arduinos: Data different after transferred.

Hi all!

I've got an Arduino Robot set up using i2c with an UNO so that the UNO - the slave - measures the data from an LDR and sends it to the Robot, which is the master.

As far as I know everything is set up correctly, however the value measured by the UNO is different to the value received by the Robot. The value read in the Serial display on the UNO is ~ 650, while the value received by the Robot is ~130.

Does anybody know what's going on and how I could solve this problem?

The code is as follows:

Master:

// robot ldr master

int SlaveID = 5;

#include <Wire.h>
#include <ArduinoRobot.h>

void setup(){
  Robot.begin();
  Serial.begin(9600);
  Wire.begin();
}

void loop(){
  Wire.beginTransmission(SlaveID);
  Wire.write(0);
  Wire.endTransmission();
  Wire.requestFrom(SlaveID, 1);
  int value = Wire.read();
  Serial.print("value: ");
  Serial.println(value);
  delay(500);
}

Slave:

//uno ldr slave
#include <Wire.h>
#include <SPI.h>
int value = 0;
char sensorPrintout[4];
void setup(){
  Serial.begin(9600);
  Wire.begin(5);
  Wire.onRequest(receiveEvent);
}

void loop(){
  value = analogRead(A0);
  Serial.println(value);
  delay(500);
}

void receiveEvent(){
  Wire.write("Value: ");
  Wire.write(value);
  delay(500);
}

For some background information: I deleted three files from the Robot Control library, as there are some incompatibilities with the Wire and ArduinoRobot libraries. The files deleted were Wire.h, Wire and twi.c . This seemed to fix the problem, as I tried a program printing 'H' or 'L' in the Robot's serial to control an LED connected to the UNO and it worked.

So anyway, does anybody have any idea what's going on?

Any input is appreciated!

You can use only one Wire.write() in the requestEvent().
You can also use no delay() no use of the Serial library in the receiveEvent() or requestEvent() functions.

And it is not normal to send string. Most of the times, just binary variables are transferred.

The receiveEvent() has a parameter "howMany", please add that to the code.
The requestEvent() occurs when the Master wants to have data, please use that in the Slave to send the value to the Master.

... and it looks like you are sending a 16-bit integer value in an 8-bit Wire.write.

The value read in the Serial display on the UNO is ~ 650, while the value received by the Robot is ~130.

(650 % 256) is 138.