STM32 I2C Slave mode HAL bug
Recently I have tried to implement a solution employing I2C interface in slave mode.
The solution follows the pattern presented in the official I2C_TwoBoards_RestartAdvComIT example available in CubeMX packages and another solution presented here: STM32F072 I2C slave Receive callback.
After fighting with incorrect timings I2C generated by CubeMX (see Possible CubeMX I2C timing config bug (STM32L0x and other)) I stumbled upon another problem: the last received frame is written twice at two consecutive buffer offsets which may result in buffer overrun and unpredictable results.
I found that the problem is caused by imperfect HAL driver code. The solution: before calling HAL_I2C_Slave_Seq_Receive_IT make sure there is more data available:
if (I2C_CHECK_FLAG(hi2c->Instance->ISR, I2C_FLAG_RXNE) == SET) ...
The problem occurs with STM32L041 and probably all recent MCUs using new I2C architecture/control registry layout. Please find details and sequence of calls in response to this post. (for any reason I am unable to add code snippets to this initial post)
Package: STM32Cube_FW_L0_V1.12.1
#I2C