2025-09-22 7:13 AM
It seems there's a bug in the HAL library causing data bytes to be mixed with memory address bytes when sending data using HAL_I2C_Mem_Write_IT function. The issue was observed on STM32L162VET6 while using I2C as master at 300kHz speed. It is caused by the condition in HAL_I2C_EV_IRQHandler (stm32l1xx_hal_i2c.c) on line 4808.
The issue happens after TXE interrupt occurs (DR is waiting for another byte of data) and your interrupt routine is not fast enough to provide DR with another byte of data, before all bits from SHIFT register are sent out. In that case, a BTF interrupt occurs, causing the code of the HAL_I2C_EV_IRQHandler to go for I2C_MasterTransmit_BTF instead of I2C_MasterTransmit_TXE function. The problem is, that I2C_MasterTransmit_BTF doesn't handle memory address. It only copies another byte of data from data buffer. The issue is invisible when the situation happens while sending out the data buffer. But if it happens during sending out the memory address it causes mixing of data byte with address bytes. That can lead to serious troubles.
Occurrence of the issue is sporadic, as the BTF interrupt must occur while sending the address bytes. But it happens. Moreover, it can be well simulated by inserting a targeted pause into the interrupt routine.