Skip to content

Commit 4146aa8

Browse files
Alberto Mannarifacchinm
Alberto Mannari
authored andcommitted
Add check for arbitration in I2C master read
Add check for errors during I2C master read (likely loss of arbitration) so that the operation can be aborted and code does not get stuck in an infinite loop
1 parent bc2c779 commit 4146aa8

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

cores/arduino/SERCOM.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ uint8_t SERCOM::readDataWIRE( void )
638638
{
639639
if(isMasterWIRE())
640640
{
641-
while( sercom->I2CM.INTFLAG.bit.SB == 0 )
641+
while( sercom->I2CM.INTFLAG.bit.SB == 0 && sercom->I2CM.INTFLAG.bit.MB == 0 )
642642
{
643643
// Waiting complete receive
644644
}

libraries/Wire/Wire.cpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,9 @@ uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit)
7878
// Read first data
7979
rxBuffer.store_char(sercom->readDataWIRE());
8080

81+
bool busOwner;
8182
// Connected to slave
82-
for (byteRead = 1; byteRead < quantity; ++byteRead)
83+
for (byteRead = 1; byteRead < quantity && (busOwner = sercom->isBusOwnerWIRE()); ++byteRead)
8384
{
8485
sercom->prepareAckBitWIRE(); // Prepare Acknowledge
8586
sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_READ); // Prepare the ACK command for the slave
@@ -88,9 +89,14 @@ uint8_t TwoWire::requestFrom(uint8_t address, size_t quantity, bool stopBit)
8889
sercom->prepareNackBitWIRE(); // Prepare NACK to stop slave transmission
8990
//sercom->readDataWIRE(); // Clear data register to send NACK
9091

91-
if (stopBit)
92+
if (stopBit && busOwner)
9293
{
93-
sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop
94+
sercom->prepareCommandBitsWire(WIRE_MASTER_ACT_STOP); // Send Stop unless arbitration was lost
95+
}
96+
97+
if (!busOwner)
98+
{
99+
byteRead--; // because last read byte was garbage/invalid
94100
}
95101
}
96102

0 commit comments

Comments
 (0)