AnsweredAssumed Answered

Bug in HAL_I2C_Master_Transmit()

Question asked by Toby on Dec 22, 2016
Latest reply on Apr 12, 2018 by j o

Recently I wasted a frustrating few days finding out why my code was unstable. Turned out to be what I believe is a bug in HAL_I2C_Master_Transmit() so I thought I should post here in case it catches anyone else out. The relevant bit of code.....

 

while(hi2c->XferSize > 0U)
{
   /* Wait until TXE flag is set */
   if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
   {
      if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
      {
         /* Generate Stop */
         hi2c->Instance->CR1 |= I2C_CR1_STOP;
         return HAL_ERROR;
      }
      else
      {
         return HAL_TIMEOUT;
      }
   }

   /* Write data to DR */
   hi2c->Instance->DR = (*hi2c->pBuffPtr++);
   hi2c->XferCount--;
   hi2c->XferSize--;

   if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0U))
   {
      /* Write data to DR */
      hi2c->Instance->DR = (*hi2c->pBuffPtr++);
      hi2c->XferCount--;
      hi2c->XferSize--;
   }

   .........

}

I think the line

if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (Size != 0U))

should actually read

if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->xferSize != 0U))

As it is, any time the xferSize is 1 at the top of the loop and the BTF flag is set it decrements xferSize past zero and it does not exit the loop correctly.

##

Outcomes