Search code examples
microcontrollerstm32i2ctemperature

Use i2C interface to read from ADT7420 temperature sensor


I am trying to set up my STM32 microcontroller with HAL libraries to read from a ADT7420 temperature sensor using i2c. However I am unable to read the correct value from the sensor as I run my code.

Here is how I have done it so far using HAL libraries:

uint8_t I2C_ADDR = 0x48;
uint8_t TEMP_CONFIG = 0x03;

uint8_t data[2];

HAL_I2C_Master_Transmit(&hi2c1, I2C_ADDR, &TEMP_CONFIG , 1, 10000);

HAL_I2C_Master_Receive(&hi2c1, I2C_ADDR, data, 2, 10000);

uint16_t temp_raw = (uint16_t)((data[0]<<8) | data[1]);
int temp_value = calc_celcius(temp_raw); //TODO: convert to Celsius

Using this code, the temperature stays at zero indicating that something is not working correctly. Am I missing some config settings for the i2c setup in order to read the temperature value? Thanks.


Solution

  • You need to send register address as a first byte of I2C write followed either by data to be written into that register, or I2C repeated start and reading the value. See page 18 and 19 in datasheet, you have linked, for details.

    It seems that HAL_I2C_Mem_Write() and HAL_I2C_Mem_Read() functions should take care of this address writing for you. So, this part of your code would look like

    HAL_I2C_Mem_Write(&hi2c1, I2C_ADDR, 0x03, I2C_MEMADD_SIZE_8BIT, &TEMP_CONFIG , 1, 10000);
    HAL_I2C_Mem_Read(&hi2c1, I2C_ADDR, 0x00, I2C_MEMADD_SIZE_8BIT, data, 2, 10000);
    

    Disclaimer: I have no experience with just HAL library, so my answer is based on quick read through documentation and source code provided only.

    Note also that directly after powering up the IC, you need to wait for first conversion to complete in order to get non-zero value. According to the datasheet, first conversion should be done in 6 ms only (with low precision), each other conversion in normal mode takes 240 ms.