More than 1 bytes not being properly sent through I2C?

Hi,

I have been banging my head for the last hours with this and I don't understand what is wrong. I have two Arduinos connected to each other via I2C. I simply want the master to just request two bytes from the slave. I am basically using the sketches found on the Arduino website. Pasting them below:

Master Receive

#include <Wire.h>

void setup() {
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);
}

void loop() {
  Wire.requestFrom(8, 2);    // request 2 byte from slave device #8
  while (Wire.available()) { // slave may send less than requested
    Serial.println(Wire.read()); //Write what you receive
  }
  delay(100);
}

Slave send

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop() {
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write(66);
  Wire.write(40);
}

As you can see, it is (or should be) very straight forward. In the master, I am expecting to receive the two values that I send in requestEvent. 66 and 40. However, I always receive 255 and 40 instead.

Am I missing something very obvious here?! Because this is really frustrating... >:(

The behaviour of Wire.write() is asymmetric; its behaviour depends on whether you're a master or slave.

Calling write() from the master fills a 32-byte buffer which is transmitted when endTransmission() is called.

Calling write() from the slave sends the data immediately. If you call write(uint8_t), you send one byte and extra
bytes requested by the master are garbage.

To send multiple bytes from the slave, you have to fill your own buffer and send it all at once.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
}

void loop() {
  delay(100);
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  //Wire.write(66);
  // Wire.write(40);
  uint8_t buffer[2];
  buffer[0] = 66;
  buffer[1] = 40;
  Wire.write(buffer, 2);
}

Yeah, I figured that out soon after posting this topic. Anyway, apparently there is some other mysterious behavior that I have to solve now... :stuck_out_tongue:

Thanks eitherhow! :slight_smile:

Anyway, apparently there is some other mysterious behavior that I have to solve now

I'll bet it involves the code you didn't post, and some other incorrect assumptions (that we could help you straighten out in seconds).