Hi,
I'll reply to my own question and post the answer here as this will probably help anyone using an STM32 controller. Below is the I2C send and receive functions. Happy coding.
****************************************************************************************************************************************************************
int8_t user_i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)
{
int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */
HAL_StatusTypeDef status;
// The device address is shared with I2C and SPI.
// When using SPI, it works on 7 bit mode.
// When using I2C, it works on 8 bit mode and we have to left shift the 7 bits.
// DOCS REFS: Datasheet Sections 6.
// Waiting for I2C to get freed from HAL bondage
while(HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t) (dev_id << 1), 1, 100) != HAL_OK);
//HAL is never Ok, but we'll accept it
if(HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t) (dev_id << 1), 1, 100) == HAL_OK)
{
// Writing register address to the slave
status = HAL_I2C_Master_Transmit(&hi2c1, (uint16_t) (dev_id << 1), ®_addr, sizeof(reg_addr), 100);
if(status != HAL_OK) rslt = -1;
// Reading registers starting from the sent address to the len
status = HAL_I2C_Master_Receive(&hi2c1, (uint16_t) (dev_id << 1), reg_data, len, 100);
if(status != HAL_OK) rslt = -1;
}
else
{
//do something, anything. print optional
//printf("I2C is busy...\r\n");
rslt = -1;
}
return rslt;
}
int8_t user_i2c_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *reg_data, uint16_t len)
{
int8_t rslt = 0; /* Return 0 for Success, non-zero for failure */
// The device address is shared with I2C and SPI.
// When using SPI, it works on 7 bit mode.
// When using I2C, it works on 8 bit mode and we have to left shift the 7 bits.
// DOCS REFS: Datasheet Sections 6.
// Waiting for I2C to get freed
while(HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t) (dev_id << 1), 1, 100) != HAL_OK);
if(HAL_I2C_IsDeviceReady(&hi2c1, (uint16_t) (dev_id << 1), 1, 100) == HAL_OK)
{
// We dont need to send stop bit when writing to sensor, a blocking mode direct write can be called here.
HAL_I2C_Mem_Write(&hi2c1, (uint16_t) (dev_id << 1), reg_addr, sizeof(reg_addr), reg_data, len, 100);
}
else
{
//printf("I2C is busy...\r\n");
rslt = -1;
}
return rslt;
}