Incomplete example for wire.read()? - Returns a byte instead (documented) char?

Hi,

I had some problems with receiving binary data over I2C:

The example here WireRead states receiving data is as easy as (note inparticular char c):

char c = Wire.read();

But as stated here: github stream read() the read function returns bytes

The first byte of incoming data available

I was sending hex-data (bytes) over I2C to the arduino, e.g. 0x07, which was happily stored in the char c.
But testing other bytes, like 0x88 failed, printed received characters as "ff88". I belive it is due to the fact that char can only hold integers from -127..127 while 0x88 is more like 144(int) which could be stored in a byte variable (0..255) but not in a char

So my question is: should the example be changed and use a byte data type?
But since read() can also return -1, should the example use int?

byte c = Wire.read();
int c = Wire.read();

So my question is: should the example be changed and use a byte data type?

Yes. The function returns a byte, which is an unsigned value, not a char, which is a signed value.

But since read() can also return -1, should the example use int?

It will only return -1 (255) when you call it without checking that there is anything available() to be read. If you check that there is data to be read before trying to read() it, then byte is fine as the type.

The Wire.read() returns a signed integer: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/Wire/src/Wire.cpp#L243.

That integer is the byte value 0...255 of the data, or else it is -1 when there was nothing available (in the internal buffer in the Wire library).

These are both correct:

byte c = Wire.read();
int c = Wire.read();

When no problems are expected, the return value can be copied into a byte. If you want to test for the -1 value, you have to use an integer.

A I2C bus should work okay, or else there is a serious hardware problem. Just a simple check in the beginning to test if the sensor is connected is often enough. In the sketch, you should only do a Wire.read() when there is data available. Therefor testing for the return value of -1 is often not needed.

So, since this seems to be an error or rather an incompleteness in the official sample code (and a quick google search shows that this type of casting to an char is very commonly used) what are the steps to change the sample code to a version with int?

int c = Wire.read();

Bytes are transferred, not integers.
If you want to transfer an integer, you have to use two bytes.