Strange code in I2C code…

Published on 2011-10-14 by Mark VandeWettering

I noticed something while reading code that uses the Wire library for the Arduino, such as you might find below…

Arduino playground – I2CEEPROM

Check out this two line fragment from the read function:

for ( c = 0; c < length; c++ )
      if (Wire.available()) buffer[c] = Wire.receive();

Is anyone else struck by the fact that it is, well, just wrong? The I2C device is expected to be sending "length" bytes. This loop checks to see if a byte is available, and if it is, then sticks it in the buffer. But what happens if it is not? Then the index increments, and when we try again, any particular byte we write will be placed at a strange location in the buffer.

The only way this code makes sense is if Wire.available() never fails. If it does, then it will leave an empty slot in the output array.

I'll have to step through the Wire library source to make sure, but this seems wrong to me. I'll let you know what I find.