I have two Arduino unos, and I am using I2C to have them communicate with each other. The A4, A5, and GND of each Arduino is connected to the other. These are my functions:

On the sending Arduino:

void playNote(int pitch, int len, int location){
  Serial.println(String(String(location) + ":" + String(pitch) + "," + String(len) + "\n"));

On the receiving Arduino:

void receiveEvent(int howMany){
  int pitch = Wire.read();
  int len = Wire.read();
  Serial.println("Pitch: " + String(pitch) + ", Length: " + String(len));

pitch always sends fine. When I send len as 150, it works and is received as 150. However, when len is sent as 300, it is received as 44. I cannot figure out why this is. Any help is appreciated.


wire.write(n) sends a single byte of value n

150 decimal = 96 Hex
300 decimal = 012C Hex ...so is 2 bytes, and is truncated to one byte of value 2C Hex.

2C Hex = 44 decimal

Send a single byte! Maximum value of a byte is 255 decimal

If you need to send multiple Len bytes, then you need to ascertain the number of bytes and send them individually. In your code you send multiple bytes concatenated one after the other already ...you send Pitch followed by Len.
All you need to do is split Len into L1, L2 bytes first.

L1 = Len and xFF
Shift Len left or do other logical math to derive high byte, L2
Then send L1 and L2

  • 1
    Thanks, but I need to send 2 bytes. Do you know of an easy way to do this?
    – Cameron K
    Oct 16 '17 at 3:15
  • 1
    You simply need to split Len into discrete bytes, send sequentially and reassemble at the Rx. Oct 16 '17 at 3:22
  • it is not really true that you need to send them individually, there is also a form of write() which takes a pointer and count. Since both receiver and transmitter have the same means of encoding an int, you can do this directly using a pointer to it, and of course the applicable size of an int which under avr-gcc is 2 bytes. Oct 17 '17 at 3:39
  • @ChrisStratton....of course that's true but I wanted to keep it simple for the OP using wire.write() as I assumed the OP was new to this. Had he/she looked up the documentation it would have been clear. Oct 17 '17 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.