Hardware Reference
In-Depth Information
Wire.write(config); //configure with options
Wire.endTransmission();
startConversion();
}
float DS1631::getTemp() //0xAA command Read Temp, read 2 bytes, one shot temperature read
{
unsigned char _temp[2];
int count = 0;
Wire.beginTransmission(_addr);
Wire.write(0xAA); // start reading temperature now
Wire.endTransmission();
delay(750); //750ms reqiured to get 12 bit resolution temperature
Wire.requestFrom(_addr, (uint8_t)2); //get the 2 byte two's complement value back
while(Wire.available())
{
_temp[count] = Wire.read();
count++;
}
float temp = calcTemp(_temp[0],_temp[1]);
return temp;
}
float DS1631::calcTemp(int msb, int lsb)
{
float num = 0.0;
//Acceptable, but only 2-3 significant digits
// num = ((((short)msb<<8) | (short)lsb)>>6) / 4.0;
lsb = lsb >> 4; // shift out the last 4 bits because they are 0
if (msb & 0x80) // Compare the sign bit = 1, then less than 0;
{
msb = msb - 256;
}
// Float conversion
num = (float) (msb + lsb*0.0625);
return num;
}
The work of implementing the header file is done in the implementation file. Each of the I2C commands needs
to be configured exactly to the data sheet. The constructor takes the defined address and shifts it the required one bit
in order to be a proper address on the I2C bus. The details of the I2C communication protocol are wrapped inside the
functions so that a library user only needs to have some knowledge of the data sheet.
We have a setConfig(uint8_t) and a uint8_t getConfig() that will accept and display the configuration of the
temperature sensor.
The datasheet explains that the temperature is in Celsius and is stored in two's complement formats, which
mean that the most significant bit is the whole number, and the least significant bit is the decimal place. The float
getTemp() function returns the Celsius temperature by calling calcTemp() ; this is a private function that the sketch
cannot call. There are many ways to do calcTemp() ; it could be turned into a virtual function and be overridden by the
programmer, but by separating it from getTemp() , it is possible to add flexibility to the library.
 
Search WWH ::




Custom Search