cancel
Showing results for 
Search instead for 
Did you mean: 

STM32L0C8T6 failed to communicate with M24C02 through IIC

*于.1
Associate II

STM32L0C8T6 failed to communicate with M24C02 through IIC,iic uses cubemx default configuration,The relevant code show as below:

#define ADDR_24LCxx_Write 0xA0

#define ADDR_24LCxx_Read 0xA1

#define IIC_BufferSize 256

uint8_t IIC_WriteBuffer[IIC_BufferSize],IIC_ReadBuffer[IIC_BufferSize];

uint8_t IIC_flag = 0;

HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, GPIO_PIN_SET);  //eeprom power on

​IIC_WriteBuffer[0] = 0x01;

IIC_WriteBuffer[1] = 0x02;

IIC_flag = HAL_I2C_Mem_Write(&hi2c1, ADDR_24LCxx_Write, 0, I2C_MEMADD_SIZE_8BIT,IIC_WriteBuffer,8, 1000);

if(IIC_flag == HAL_OK)

{

sprintf(string,"IIC write succeed!\r\n"); 

HAL_UART_Transmit(&huart1,(uint8_t*)string,strlen((char *)string),1000);

}

else

{

sprintf(string,"IIC write falsed!IIC_flag: %d\r\n",IIC_flag); 

HAL_UART_Transmit(&huart1,(uint8_t*)string,strlen((char *)string),1000);

}

Online debugging code stops here:

  /* Send Slave Address and Memory Address */

  if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)

  {

   if (hi2c->ErrorCode == HAL_I2C_ERROR_AF)

   {

    /* Process Unlocked */

    __HAL_UNLOCK(hi2c);

    return HAL_ERROR;

   }

   else

   {

    /* Process Unlocked */

    __HAL_UNLOCK(hi2c);

    return HAL_TIMEOUT;

   }

  }

sch:

0693W000006HdlxQAC.png

2 REPLIES 2
Peter BENSCH
ST Employee

Please add a few milliseconds delay after switching on the EEPROM, like:

HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, GPIO_PIN_SET);  //eeprom power on
HAL_Delay(10);
IIC_WriteBuffer[0] = 0x01;

What frequency do you set the I2C clock to?

BTW: to make the source code more readable, please use the </> button to include it.

Regards

/Peter

In order to give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.
AIM65
Associate III

In addition with the startup delay recommanded in the previous post; usually, with I2C memory device, more when they're as old as an 24C02, one should check if device is ready before any read or write operation, HAL propose this feature : HAL_I2C_IsDeviceReady(). Example code :

//Read one or several byte from EEPROM

void EEPROM_RD(uint16_t Addr, uint16_t nbyte, uint8_t* pdata)

{

if (HAL_I2C_IsDeviceReady(&hi2c1, EEPROM_BASEADDR, I2CRETRY, I2CXTIMEOUT)!= HAL_OK) I2Cx_Error();

if (HAL_I2C_Mem_Read(&hi2c1, EEPROM_BASEADDR, Addr, I2C_MEMADD_SIZE_16BIT,pdata, nbyte, I2CXTIMEOUT) != HAL_OK) I2Cx_Error();

}

Number of retry and timeout duration could be high for safe operation with old device, for example :

#define I2CXTIMEOUT 20 //20ms

#define I2CRETRY 80

with a 64MHz f030 MPU and a 24c16.