MCP9808 | STM32 I2C Interface
MCP9808 | STM32 I2C Interface

The MCP9808 digital temperature sensor converts temperatures between -40°C and +125°C to a digital word with ±0.5°C (max.) accuracy. The sensor registers can be configure for temperature Alert window limits and critical output limits.When the temperature changes beyond the specified boundary limits, the MCP9808 outputs an Alert signal. The sensor supports I2C protocol with 400Khz speed. The sensor is best suited for temperature-monitoring applications.

I have written a simple C library for MCP9808 temprature with STM32F44RE nucleo as a host controller board which can be replaced very easily.

MCP9808 Pinout

MCP9808 is interfaced with I2C1 with PB8 and PB9 pins. The I2C interface is configured in I2CInit() function. If other controller is used to interface MCP9808 just change the I2CInit() functionallity according to selected controller. The address pins A0,A1 and A2 define the address since all are connected to ground the address of MCP9808 is 0x18.

void mcp9808Start(void)
{
  float temprature;

  I2CInit();
  mcp9808Struct mcp9808 = {0};
  
  uartSend("Welcome To Embedded Diaries\r\n");
  
  if(mcp9808ReadReg(DEVICEIDREVISION,data) != true)
  {
        uartSend("MCP9808 not found\r\n");
  }
  if(data[0] == DEVICEID)
  {          
    mcp9808Config(mcp9808);
    while(1)
    {
        temprature = getTempratureValue();
        sprintf((char*)buff,"Temprature value = %.2f\r\n",temprature);
        uartSend(buff);
        HAL_Delay(1000);
    }
  }
}

Function mcp9808Start() will print the temprature value in float every 1 second. In case host contoller other than STM32 is selected then modify the mcp9808ReadReg() and mcp9808WriteReg() function according to controller requirements.

static status mcp9808WriteReg(uint8_t reg,uint8_t *data)
{
  uint8_t writeBuff[3] = {0};
  writeBuff[0] = reg;
  writeBuff[1] = data[1];
  writeBuff[2] = data[0];
  
  if( HAL_I2C_Master_Transmit(&hi2c1,MCP9808ADDRESS,writeBuff,3,HAL_MAX_DELAY) != HAL_OK)
  {
    return false;
  }
  
  return true;
}

Function mcp9808WriteReg() will used to write MSB and LSB bytes of MCP9808.

status mcp9808ReadReg(uint8_t reg,uint8_t *data)
{
  if( HAL_I2C_Master_Transmit(&hi2c1,MCP9808ADDRESS,&reg,1,HAL_MAX_DELAY) != HAL_OK)
  {
    return false;
  }
  
  if( HAL_I2C_Master_Receive(&hi2c1,MCP9808ADDRESS,data,2,HAL_MAX_DELAY) != HAL_OK)
  {
    return false;
  }
  
  return true;
}

Function mcp9808ReadReg() used to read MSB and LSB byte of MCP9808.

Uart Output