Help with negative numbers in library for TMP102

Hi,

I have been using the library below for the TMP102 temperature sensor - recently I noticed that it doesn't handle negative temperatures correctly so instead of counting -1, -2, -3 etc it reports 254, 253, 252 etc..... can anyone provide some help on how to resolve this please? Thanks :slight_smile:

#include "TMP102.h"

void TMP102::readTemperatureRegister(void)
{

  unsigned char MSB,LSB;

  Wire.beginTransmission(TMP102_ADDRESS); //TMP102 Device (I2C Slave) address
  Wire.send(0x00); //Temperature registers starts at address 0x00
  Wire.endTransmission();

  Wire.requestFrom(TMP102_ADDRESS, 2);  
   
  MSB = Wire.receive();  //Read MSB of Temperature Register
  LSB = Wire.receive();  //Read LSB of Temperature Register

  /*
  Temperature Register Format:
 
  MSB:  T11 T10 T9 T8 T7 T6 T5 T4
  LSB:  T3  T2  T1 T0 0  0  0  0
  */

  temperature = (MSB << 8 )  | LSB; 
  temperature >>= 4 ;   // Value is left shifted in above table. Hence Right shift.
  temperature = temperature & 0xFFF; //temperature is integer. Remove extra bits.


  if(temperature & 0b100000000000) //T11 indicates sign (either +ve or -ve)
  {
   //Negative temperature 
   //Negative numbers are represented in binary two's complement format according to data sheet
    temperature = temperature - 1;
    temperature ^= 0xFFF;
    temperatureCelsius = temperature * 0.0625 * (-1); //Each bit is 0.0625 deg Celsius
  }
  else
  {
   //Positive temperature 
    temperatureCelsius = temperature * 0.0625;
  }
}

//Return temperature (each bit indicates 0.0625 deg celsius)
int TMP102::getTemperature(void)
{
 readTemperatureRegister();
 return temperature;
}

//Return temperature in celsius
float TMP102::getTemperatureInCelsius(void)
{
 readTemperatureRegister();
 return temperatureCelsius;
}

TMP102 Tmp102; //Create object

Are you reading to a byte or to an int. feed a -1 to a byte and you will get 255 - all bits on = -1

Hi Kf2qd,

The value is an int I think - the header file is below.... not sure of the implications though...

#ifndef TMP102_h
#define TMP102_h

//**********************************************
#include <WProgram.h>
#include <Wire.h>

#define TMP102_ADDRESS 72 // I2C device address 

class TMP102 
{
public:
int getTemperature(void);
float getTemperatureInCelsius(void);

private:
int temperature; 
float temperatureCelsius;

void readTemperatureRegister(void);

};

extern TMP102 Tmp102;

#endif