Sunday, April 28, 2013

Reading Temperature from a TMP102 Thermometer with pcDuino (C Version)

My previous post on reading the temperature from a TMP102 using a pcDuino used a Python script. Here is an example using C. For information on the connections and prerequisites, see the Python version of this post: Reading Temperature from a TMP102 Thermometer with pcDuino (Python Version).

Code


#include <stdio.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>

int main (void)
{
int deviceHandle;
int readBytes;
char buffer[2];
// initialize buffer
buffer[0] = 0x00;
int deviceI2CAddress = 0x48;
// open device on /dev/i2c-2
if ((deviceHandle = open("/dev/i2c-2", O_RDWR)) < 0) {
printf("Error: Couldn't open device! %d\n", deviceHandle);
return 1;
}
// connect as i2c slave
if (ioctl(deviceHandle, I2C_SLAVE, deviceI2CAddress) < 0) {
printf("Error: Couldn't find device on address!\n");
return 1;
}    
// begin transmission and request acknowledgement
readBytes = write(deviceHandle, buffer, 1);
if (readBytes != 1)
{
printf("Error: Received no ACK-Bit, couldn't establish connection!");
}
else
{
// read response
readBytes = read(deviceHandle, buffer, 2);
if (readBytes != 2)
{
printf("Error: Received no data!");
}
else
{
// get data
int msb = buffer[0];
int lsb = buffer[1];
double temp = (((msb << 8) | lsb) >> 4) * 0.0625;
// and print results
printf("Temp: %0.2f C\n", temp);
}
}
// close connection and return
close(deviceHandle);
return 0;
}

Compiling & Running


Compiling the program is easy. Assuming you have saved the code to a file named tmp102.c, change directory to the location of the code file and compile using gcc -

  gcc tmp102.c -otmp102

This produces an executable named tmp102.  Run the program by typing ./tmp102 

3 comments:

  1. First shot first goal!Works perfectly. Thanks Brad.

    ReplyDelete
  2. Very usefull tutorial. We forward your post to learn.linksprite.com. If you have any other new post about pcDuino(www.pcduino.com) or any other LinkSprite's(www.linksprite.com) products, please feel free to let us know. If you have a new post, could you please give us a backlink?

    ReplyDelete