Skip to content

Commit a8b801d

Browse files
committed
[I2C] Harden error management
Example for I2C scanner fewer errors are reported. Sometime there is a HAL_I2C_ERROR_TIMEOUT was raised but not reported as I2C_TIMEOUT. In a general way, mask have to be used to properly handle error cases. Signed-off-by: Frederic.Pillon <[email protected]>
1 parent 8134a78 commit a8b801d

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

Diff for: cores/arduino/stm32/twi.c

+12-6
Original file line numberDiff line numberDiff line change
@@ -723,16 +723,19 @@ i2c_status_e i2c_master_write(i2c_t *obj, uint8_t dev_address,
723723
while ((HAL_I2C_GetState(&(obj->handle)) != HAL_I2C_STATE_READY)
724724
&& (ret == I2C_OK)) {
725725
delta = (HAL_GetTick() - tickstart);
726-
if (delta > I2C_TIMEOUT_TICK) {
726+
uint32_t err = HAL_I2C_GetError(&(obj->handle));
727+
if ((delta > I2C_TIMEOUT_TICK)
728+
|| ((err & HAL_I2C_ERROR_TIMEOUT) == HAL_I2C_ERROR_TIMEOUT)) {
727729
ret = I2C_TIMEOUT;
728-
} else if (HAL_I2C_GetError(&(obj->handle)) != HAL_I2C_ERROR_NONE) {
730+
} else if (err != HAL_I2C_ERROR_NONE) {
729731
ret = I2C_ERROR;
730732
}
731733
}
732734
}
733735
/* When Acknowledge failure occurs (Slave don't acknowledge it's address)
734736
Master restarts communication */
735-
} while (HAL_I2C_GetError(&(obj->handle)) == HAL_I2C_ERROR_AF && delta < I2C_TIMEOUT_TICK);
737+
} while (((HAL_I2C_GetError(&(obj->handle)) & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF)
738+
&& (delta < I2C_TIMEOUT_TICK));
736739

737740
return ret;
738741
}
@@ -784,16 +787,19 @@ i2c_status_e i2c_master_read(i2c_t *obj, uint8_t dev_address, uint8_t *data, uin
784787
while ((HAL_I2C_GetState(&(obj->handle)) != HAL_I2C_STATE_READY)
785788
&& (ret == I2C_OK)) {
786789
delta = (HAL_GetTick() - tickstart);
787-
if (delta > I2C_TIMEOUT_TICK) {
790+
uint32_t err = HAL_I2C_GetError(&(obj->handle));
791+
if ((delta > I2C_TIMEOUT_TICK)
792+
|| ((err & HAL_I2C_ERROR_TIMEOUT) == HAL_I2C_ERROR_TIMEOUT)) {
788793
ret = I2C_TIMEOUT;
789-
} else if (HAL_I2C_GetError(&(obj->handle)) != HAL_I2C_ERROR_NONE) {
794+
} else if (err != HAL_I2C_ERROR_NONE) {
790795
ret = I2C_ERROR;
791796
}
792797
}
793798
}
794799
/* When Acknowledge failure occurs (Slave don't acknowledge it's address)
795800
Master restarts communication */
796-
} while (HAL_I2C_GetError(&(obj->handle)) == HAL_I2C_ERROR_AF && delta < I2C_TIMEOUT_TICK);
801+
} while (((HAL_I2C_GetError(&(obj->handle)) & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF)
802+
&& (delta < I2C_TIMEOUT_TICK));
797803

798804
return ret;
799805
}

Diff for: libraries/Wire/src/Wire.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ uint8_t TwoWire::endTransmission(uint8_t sendStop)
247247
//
248248
uint8_t TwoWire::endTransmission(void)
249249
{
250-
return endTransmission(true);
250+
return endTransmission((uint8_t)true);
251251
}
252252

253253
// must be called in:

0 commit comments

Comments
 (0)