If you want a good night sleep try reading and fully understanding it`s pdf document .
I can now understand just about any spi or i2c device document, But this a is most harder to decipher.
http://www.ti.com/lit/ds/symlink/tmp102.pdf
How to read from the chip :
It`s I2C address depend on where you connect the ADD0 too.
Ground = 0x48 , V+ = 0x49 , SDA = 0x4A , SCL = 0x4B
Read two Bytes ( High byte is first followed by the Low byte )
High byte ( Full degrees )
Low byte ( fraction degrees )
To get the temperature
Multiply the Hi_byte by 16 ( << 4 ) + Divide Low_byte by 16 ( >> 4 )
Now multiply the result by 0.0625 and you have the temperature.
Temperature = (( Hi_byte << 4) | ( Low_byte >> 4)) * 0.0625This works if the temperature is above zero.
Minis temperature problem
The most significant bit of High byte says if the temperature is a negative or positive value.
The documents explanation on how to convert the negative value is:-
For negative temperatures (for example, –25°C):
Generate the twos complement of a negative number by complementing the absolute value binary number
and adding 1. Denote a negative number with MSB = 1.
Example: (|–25°C|)/(0.0625°C/count) = 400 = 190h = 0001 1001 0000
Twos complement format: 1110 0110 1111 + 1 = 1110 0111 0000
My way I converting this into a usable form , is to test if the most significant bit is set :-
if Hi_byte & 0x80 == 0x80:
If this is True we need to add 1 to the Hi_byte and remove any overflow and keep the value byte size :-
Hi_byte = (Hi_byte + 1 & 0xff)
This don`t work in fact , after waiting for it to freeze to test out my code.
I`ve found the way to do it , is
0 - ( 256 - Temperature )
To download the complete working code for python 3 using Quick2wire my link is below.
This can be converted to any i2c library , all you need is the High and Low byte.
https://github.com/peter247/Pi_Weather_monitor/blob/master/examples/tmp102.py
Hi.
ReplyDeleteYour code helped me a lot. But -0.1, -0.2 and -3.1 degrees showed as -0.9, -0.8 and -253.9
This is a better calculation for negative temps.
Full_word = (Hi_byte << 4) | (Low_byte >> 4)
if Hi_byte & 0x80: # Convert a 12 bit negative to a full 32 or 64 bit negative word.
Full_word = Full_word | (-1 - 0x7ff)
heat = Full_word * 0.0625
return heat