arduino / arduino/ArduinoCore-avr

Wire.h: Wrong number of bytes returned from the slave device (I2C)

Open
#384 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
C
Stars
1.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

Hi. According to the documentation, the two functions below will return the number of bytes that the master has received from the slave and which are available in the buffer.

> [Wire.requestFrom()](https://www.arduino.cc/en/Reference/WireRequestFrom)
> Description
> Used by the master to request bytes from a slave device.
> Returns
> byte : the number of bytes returned from the slave device

> [Wire.available()](https://www.arduino.cc/en/Reference/WireAvailable)
> Description
> Returns the number of bytes available for retrieval with read().
> Returns
> The number of bytes available for reading.

But if slave will respond with a less number of bytes than master requested (as is described in [Master Reader/Slave Sender Example](https://www.arduino.cc/en/Tutorial/LibraryExamples/MasterReader)), then we have a problem because both functions ([Wire.requestFrom()](https://www.arduino.cc/en/Reference/WireRequestFrom) and [Wire.available()](https://www.arduino.cc/en/Reference/WireAvailable)) will return the requested number of bytes, not the number of bytes received from slave. So, the output will be `hello ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮`.

**master_reader.ino**
```
#include

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

void loop() {
Wire.requestFrom(8, 32); // request 32 bytes from slave device #8

while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}

delay(500);
}
```

**slave_sender.ino**
```
#include

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("hello "); // respond with message of 6 bytes
// as expected by master
}
```

It will be great if it will be fixed.

Regards,
Florin.

Contributor guide

No contributing guide indexed for this repository

Research direction

Reproduce the behavior with master_reader.ino and slave_sender.ino, starting at the Wire.requestFrom() and Wire.available() entry points. Done means a slave response shorter than the requested length reports and reads only the bytes actually received, without trailing garbage.

Written by the indexing model from the issue text.

Assessment

Tech stack
arduino, c
Domain
embedded-iot
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.