- http://uk.farnell.com/microchip/mcp9808 ... dp/2080523
Wiring it all is fine. "i2cdetect -y 1" gives 0x18 and I can read 3 bytes from the device.
However, I can't get a proper temperature reading using the following code. What's wrong
is that it's not accepting my command or I'm not transmitting data in the correct order:
Code: Select all
class tempSensorMCP9808(i2c_device):
"""
MCP9808 is an I2C Temperature sensor
"""
def read_temperature(self):
self.write(0x05)
s = 0
b = self.read_nbytes_data(s,3)
t = b[1] & 0x0f + b[2]
return t
The datasheet gives this code:
Code: Select all
i2c_start(); // send START command
i2c_write (AddressByte & 0xFE); //WRITE Command (see Section 4.1.4 “Address Byte”)
i2c_write(0x05); // Write TA Register Address
//also, make sure bit 0 is cleared ‘0’
i2c_start(); //Repeat START
i2c_write(AddressByte | 0x01); // READ Command (see Section 4.1.4 “Address Byte”)
UpperByte = i2c_read(ACK); // READ 8 bits
LowerByte = i2c_read(NAK); // READ 8 bits
i2c_stop(); // send STOP command
//also, make sure bit 0 is Set ‘1’
//and Send ACK bit
//and Send NAK bit
//Convert the temperature data
//First Check flag bits
if ((UpperByte & 0x80) == 0x80){
//TA 3 TCRIT
}
if ((UpperByte & 0x40) == 0x40){
//TA > TUPPER
}
if ((UpperByte & 0x20) == 0x20){
//TA < TLOWER
}
UpperByte = UpperByte & 0x1F; //Clear flag bits
if ((UpperByte & 0x10) == 0x10){ //TA < 0°C
UpperByte = UpperByte & 0x0F;
//Clear SIGN
Temperature = 256 - (UpperByte x 16 + LowerByte / 16);
}else
//TA
3 0°C
Temperature = (UpperByte x 16 + LowerByte / 16);
//Temperature = Ambient Temperature (°C)