// File: lm75a.cpp // Continously read the temperature from a lm75a and display it. // Author: Jim Merkle, 03/30/2017 #include #include #include #include #include #include #include #include #include #include #include #include #define PROG_NAME "lm75a" // I2C Address #define LM75A 0x48 // LM75A Registers #define LM75A_REG_TEMP 0 #define LM75A_REG_CONF 1 #define LM75A_REG_THYST 2 #define LM75A_REG_TOS 3 #define LM75A_REG_PROD_ID 7 /* only applicable for TI manufactured part */ // Power On Defaults: // 0: Read only temperature - 2 bytes // 1: 0x00 Configuration // 2: 0x4B THYST - 75 degrees C - 2 bytes // 3: 0x50 TOS - 80 degrees C - 2 bytes // 7: 0xA1 (TI only) int main(int argc, char * argv[]) { // Open the i2c bus device where the chip resides int fd = open("/dev/i2c-1",O_RDWR); if(fd<0) { printf("Failed to open the bus."); /* ERROR HANDLING; you can check errno to see what went wrong */ exit(1); } // By default, the LM75A configuration register is 0x00 // Continously display the temperature every second while (1) { uint8_t index = LM75A_REG_TEMP; // Read temperature register uint8_t temperatureRegs[2]; // The MSB (first byte) is degree C units, the LSB is fractional component struct i2c_msg msg[2]; // declare a two i2c_msg array struct i2c_rdwr_ioctl_data i2c_data; // Load up first message - writing index to device msg[0].addr = LM75A; msg[0].flags = 0; msg[0].buf = &index; msg[0].len = 1; // Load up read message msg[1].addr = LM75A; msg[1].flags = I2C_M_RD; msg[1].buf = temperatureRegs; msg[1].len = 2; i2c_data.msgs = msg; // point to struct i2c_msg array i2c_data.nmsgs = 2; // quantity of struct i2c_msg // This function call returns the number of i2c_msg structures processed, // or a negative error value int result = ioctl(fd,I2C_RDWR,&i2c_data); if(result < 0) { printf("ioctl error: %s\n", strerror(errno)); return -2; } // Combine the two bytes into a 16-bit value uint16_t uTemp = (uint16_t)temperatureRegs[0] << 8 | (uint16_t)temperatureRegs[1]; // high byte followed by low byte float fTemp = (short)uTemp; fTemp /= 256; // The float will keep the remainder // Convert into Fahrenheit float fTempf = fTemp*9/5 + 32; // Display the two bytes of data, and floating point temperature in degrees C printf("0x%04X %0.3fC ",uTemp,fTemp); printf("%0.1fF\n",fTempf); // Display temperature in degrees F sleep(1); } // clean up close(fd); return 0; }