Skip to content

Commit d0ce315

Browse files
committed
Use interrupt mode for I2C transfers
Switch from polling mode to IT mode for I2C transfers. For example, this is needed if we want to use SPI and I2C in the same time.
1 parent 156ccfc commit d0ce315

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

cores/arduino/stm32/twi.c

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -255,14 +255,12 @@ void i2c_custom_init(i2c_t *obj, i2c_timing_e timing, uint32_t addressingMode, u
255255

256256
handle->State = HAL_I2C_STATE_RESET;
257257

258-
if(master == 0) {
259-
HAL_NVIC_SetPriority(obj->irq, 0, 1);
260-
HAL_NVIC_EnableIRQ(obj->irq);
258+
HAL_NVIC_SetPriority(obj->irq, 0, 1);
259+
HAL_NVIC_EnableIRQ(obj->irq);
261260
#ifdef STM32F1xx
262-
HAL_NVIC_SetPriority(obj->irqER, 0, 1);
263-
HAL_NVIC_EnableIRQ(obj->irqER);
261+
HAL_NVIC_SetPriority(obj->irqER, 0, 1);
262+
HAL_NVIC_EnableIRQ(obj->irqER);
264263
#endif
265-
}
266264

267265
// Init the I2C
268266
HAL_I2C_Init(handle);
@@ -338,7 +336,10 @@ i2c_status_e i2c_master_write(i2c_t *obj, uint8_t dev_address,
338336
HAL_StatusTypeDef status = HAL_OK;
339337

340338
// Check the communication status
341-
status = HAL_I2C_Master_Transmit(&(obj->handle), dev_address, data, size, I2C_TIMEOUT_TICK);
339+
status = HAL_I2C_Master_Transmit_IT(&(obj->handle), dev_address, data, size);
340+
341+
// wait for transfer completion
342+
while(HAL_I2C_GetState(&(obj->handle)) != HAL_I2C_STATE_READY){};
342343

343344
if(status == HAL_OK)
344345
ret = I2C_OK;
@@ -380,9 +381,11 @@ i2c_status_e i2c_master_read(i2c_t *obj, uint8_t dev_address, uint8_t *data, uin
380381
{
381382
i2c_status_e ret = I2C_ERROR;
382383

383-
if(HAL_I2C_Master_Receive(&(obj->handle), dev_address, data, size, I2C_TIMEOUT_TICK) == HAL_OK) {
384+
if(HAL_I2C_Master_Receive_IT(&(obj->handle), dev_address, data, size) == HAL_OK) {
384385
ret = I2C_OK;
385386
}
387+
// wait for transfer completion
388+
while(HAL_I2C_GetState(&(obj->handle)) != HAL_I2C_STATE_READY){};
386389

387390
return ret;
388391
}

0 commit comments

Comments
 (0)