1. # Read temperature via I2C from DS1621
  2. # Customize the code according your device name
  3. # Copyleft 2013 Chaosdorf
  4.  
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <fcntl.h>
  8. #include <stdlib.h>
  9. #include <linux/i2c-dev.h>
  10.  
  11. int main(void)
  12. {
  13. int file;
  14. char filename[20];
  15. int addr = 0x48; /* The I2C address */
  16. int32_t temperature;
  17. int32_t temp_int;
  18. int32_t temp_counter;
  19. int32_t temp_slope;
  20.  
  21. // Open a file giving access to i2c interface 1
  22.  
  23. sprintf(filename,"/dev/i2c-1");
  24. if ((file = open(filename,O_RDWR)) < 0) {
  25. printf("No access\n");
  26. exit(1);
  27. }
  28.  
  29. // Check that the chip is there
  30.  
  31. if (ioctl(file,I2C_SLAVE,addr) < 0) {
  32. printf("No chip detected\n");
  33. exit(1);
  34. }
  35.  
  36. // Set up continuous measurement
  37.  
  38. if (i2c_smbus_write_byte_data(file, 0xac, 0x00) < 0) {
  39. printf("Set continuos mesurement failed\n");
  40. exit(1);
  41. }
  42.  
  43. // Start measurements
  44.  
  45. if (i2c_smbus_write_byte(file, 0xee) < 0) {
  46. printf("Start measurements failed\n");
  47. exit(1);
  48. }
  49.  
  50. // read TEMP_INT
  51.  
  52. if ((temp_int = i2c_smbus_read_byte_data(file, 0xaa)) < 0) {
  53. printf("Read temp_int failed\n");
  54. exit(1);
  55. }
  56.  
  57. // read TEMP_COUNTER
  58.  
  59. if ((temp_counter = i2c_smbus_read_byte_data(file, 0xa8)) < 0) {
  60. printf("Read temp_counter failed\n");
  61. exit(1);
  62. }
  63.  
  64. // read TEMP_SLOPE
  65.  
  66. if ((temp_slope = i2c_smbus_read_byte_data(file, 0xa9)) < 0) {
  67. printf("Read temp_scope failed\n");
  68. exit(1);
  69. }
  70.  
  71. // calculate temperaure
  72.  
  73.  
  74. temperature = temp_int * 100 - 25 + ((temp_slope - temp_counter) * 100 / temp_slope);
  75.  
  76. printf("%d", (int32_t)temperature);
  77. close(file);
  78. exit(0);
  79. }