Skip to content

Commit 94e8a59

Browse files
Merge pull request firmata#111 from nahuel/fix-i2c-unexpected-message-size
Fix management of unexpected sized I2C replies
2 parents b07fb2e + 27f7e42 commit 94e8a59

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

examples/StandardFirmata/StandardFirmata.ino

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -111,23 +111,21 @@ void readAndReportData(byte address, int theRegister, byte numBytes) {
111111
Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom
112112

113113
// check to be sure correct number of bytes were returned by slave
114-
if(numBytes == Wire.available()) {
115-
i2cRxData[0] = address;
116-
i2cRxData[1] = theRegister;
117-
for (int i = 0; i < numBytes; i++) {
118-
#if ARDUINO >= 100
119-
i2cRxData[2 + i] = Wire.read();
120-
#else
121-
i2cRxData[2 + i] = Wire.receive();
122-
#endif
123-
}
114+
if(numBytes < Wire.available()) {
115+
Firmata.sendString("I2C Read Error: Too many bytes received");
116+
} else if(numBytes > Wire.available()) {
117+
Firmata.sendString("I2C Read Error: Too few bytes received");
124118
}
125-
else {
126-
if(numBytes > Wire.available()) {
127-
Firmata.sendString("I2C: Too many bytes received");
128-
} else {
129-
Firmata.sendString("I2C: Too few bytes received");
130-
}
119+
120+
i2cRxData[0] = address;
121+
i2cRxData[1] = theRegister;
122+
123+
for (int i = 0; i < numBytes && Wire.available(); i++) {
124+
#if ARDUINO >= 100
125+
i2cRxData[2 + i] = Wire.read();
126+
#else
127+
i2cRxData[2 + i] = Wire.receive();
128+
#endif
131129
}
132130

133131
// send slave address, register and received bytes

0 commit comments

Comments
 (0)