Skip to content

Commit 137ed67

Browse files
committed
Handle I2C scan with specific call to HAL_I2C_IsDeviceReady
When size is 0, the objective is to check if device is there and ready. A typical use case is to scan through all addresses to check for available slaves. So we're checking the various error cases to report to application.
1 parent 10925a1 commit 137ed67

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

cores/arduino/stm32/twi.c

+18-2
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,11 @@ i2c_status_e i2c_master_write(i2c_t *obj, uint8_t dev_address,
355355
uint32_t tickstart = HAL_GetTick();
356356
uint32_t delta = 0;
357357

358+
/* When size is 0, this is usually an I2C scan / ping to check if device is there and ready */
359+
if (size == 0) {
360+
return i2c_IsDeviceReady(obj, dev_address, 1);
361+
}
362+
358363
do{
359364
if(HAL_I2C_Master_Transmit_IT(&(obj->handle), dev_address, data, size) == HAL_OK){
360365
ret = I2C_OK;
@@ -447,8 +452,19 @@ i2c_status_e i2c_IsDeviceReady(i2c_t *obj, uint8_t devAddr, uint32_t trials)
447452
{
448453
i2c_status_e ret = HAL_OK;
449454

450-
if(HAL_I2C_IsDeviceReady( &(obj->handle), devAddr, trials, I2C_TIMEOUT_TICK) != HAL_OK) {
451-
ret = I2C_BUSY;
455+
switch (HAL_I2C_IsDeviceReady( &(obj->handle), devAddr, trials, I2C_TIMEOUT_TICK)) {
456+
case HAL_OK:
457+
ret = HAL_OK;
458+
break;
459+
case HAL_TIMEOUT:
460+
ret = I2C_TIMEOUT;
461+
break;
462+
case HAL_BUSY:
463+
ret = I2C_BUSY;
464+
break;
465+
default:
466+
ret = I2C_TIMEOUT;
467+
break;
452468
}
453469

454470
return ret;

0 commit comments

Comments
 (0)