TechplexEngineer
4/17/2013 - 12:10 PM

How to read from a TC74 Temperature sensor on the Raspberry Pi.

How to read from a TC74 Temperature sensor on the Raspberry Pi.

float read_temp(int address, char bus) {
  unsigned int temp = 0;
	unsigned char msb, lsb;

	int fd;										// File descriptor
	char *fileName;
	//int address = 0x49;						// Address of TP102
	unsigned char buf[10];						// Buffer for data being read/ written on the i2c bus

	if (bus == 1)
		fileName = "/dev/i2c-1";				// Name of the port we will be using
	else
		fileName = "/dev/i2c-0";

	if ((fd = open(fileName, O_RDWR)) < 0) {	// Open port for reading and writing
		printf("Failed to open i2c port\n");
		exit(1);
	}

	if (ioctl(fd, I2C_SLAVE, address) < 0) {  // Set the port options and set the address of the device we wish to speak to
		printf("Unable to get bus access to talk to slave\n");
		exit(1);
	}

	buf[0] = 0;                                // This is the register we wish to read from

	if ((write(fd, buf, 1)) != 1) {            // Send register to read from
		printf("Error writing to i2c slave\n");
		exit(1);
	}

	if (read(fd, buf, 1) != 1) {				// Read back data into buf[]
		printf("Unable to read from slave\n");
		exit(1);
	}
	else {
		temp = buf[0];
		//printf("The temperature is: %f C\n",temp);
		return temp;
		}
	}
}