This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

[FAQ] TMP112: Need Linux C code for I2C sensor

Part Number: TMP112

Tool/software:

Please provide example C code for TMP112 temperature sensor.

  • This example for TI I2C Temperature Sensors is based on examples in the Linux kernel documentation:

    https://docs.kernel.org/i2c/dev-interface.html

    https://docs.kernel.org/i2c/smbus-protocol.html

    This is userspace code that accesses a /dev/i2c device, but it could be adapted to kernel driver code.

    Use your package manager, such as apt, to install libi2c-dev and compile using the -li2c flag. 

    This was tested on a RaspberryPi 4 using a TMP112, but is compatible with any 75-like temperature sensor that has 12-bit Q4 encoding.

    Note that this code makes use of SMBus Read Word, which has the wrong endianness for most sensors. This code uses __builtin_bswap16() to perform the byte swap. 

    #include <fcntl.h>
    #include <i2c/smbus.h>
    #include <linux/i2c-dev.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/ioctl.h>
    #include <unistd.h>
    
    int main() {
      int file;
      int adapter_nr = 1; /* /dev/i2c- number */
      char filename[20];
      int addr = 0x49; /* Sensor I2C address */
      __u8 reg = 0x0;  /* Temperature register address */
      __s32 res;
    
      snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
      file = open(filename, O_RDWR);
      if (file < 0) {
        printf("Failed to open %s\n", filename);
        exit(1);
      }
    
      if (ioctl(file, I2C_SLAVE, addr) < 0) {
        printf("Failed to set address\n");
        exit(1);
      }
    
      /* need to fetch 2 bytes (16 bits) */
      res = i2c_smbus_read_word_data(file, reg);
      if (res < 0) {
        printf("smbus_read failed\n");
      } else {
        /* SMBus word is LSByte first, so we must change endianness */
        int16_t word = __builtin_bswap16(res);
        /* print result in hex */
        printf("0x%X\n", word);
        /* print result in degrees c */
        printf("%f\n", (float)(word >> 4) * 0.0625f);
      }
    
      close(file);
    }