Problem in Wire.readBytes

In i2c communication between ESP32 KC868-A16 to CYD display:

uint8_t temp[len];
Wire.readBytes(temp, len);
str = String(String((char*)temp));

After this str is normaty 4 chars longer than len!
Average 1% of lenght is +-2 . of normal.

str += (char)Wire.read();

works ok.

That only read one byte

This may be relying on temp being terminated with a null character.

Try the following (untested):

uint8_t temp[len + 1];
Wire.readBytes(temp, len);
temp[len] = '\0';
str = String(String((char*)temp));

Your topic does not seem to indicate a problem with IDE 2.x and hence has been moved to a more suitable location on the forum.

There is comming also else than 0x0 and 0xff

Maybe also a CR and LF

Not sure what you mean. Since you are converting the data to a String the assumption is that the data is valid text characters, likely either ASCII or UTF_8. An embedded 0x00 will be seen as the end of text so should not occur.

@linnalahti as @david_2018 suggested did you try adding the terminating character '\0', make sure that len is long enough to take your maximum string length plus 1

uint8_t string_length = Wire.readBytes(temp, len);
temp[string_length] = '\0';
str = String(String((char*)temp));

this is an alternate method of adding a terminator, if you don't add the terminator then str is going to contain characters from previous strings at times if the length varies.

For the base class Stream, readBytes takes an array of either uint8_t or char: no need to cast with the latter. And on ESP32 (and others, but not AVR), the String constructor -- which you only have to call once -- has an overload that takes a length. It will copy that many bytes, and then NUL-terminate its copy. So you don't have to declare an extra array element and tack on your own '\0'

    char temp[len];
    size_t got_len = Wire.readBytes(temp, sizeof(temp));
    str = String(temp, got_len);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.