Module mcp9800
[hide private]
[frames] | no frames]

Source Code for Module mcp9800

 1  # mcp9800.py 
 2  # Read temperature from MCP9800 IC 
 3  ''' 
 4  REG_TEMP: Temperature register layout  
 5  MSB         b7      b6      b5      b4      b3      b2      b1      b0 
 6  Weight      sign    64      32      16      8       4       2       1 
 7   
 8  LSB         b7      b6      b5      b4      b3      b2      b1      b0 
 9  Weight      1/2     1/4     1/8     1/16    0       0       0       0 
10   
11  Resolution in REG_CONFIG: b5, b6 
12  b6 = 0, b5 = 0 -> REG_TEMP: b4 = b5 = b6 = 0; b7 valid (1/2 degrees resolution) 
13  b6 = 0, b5 = 1 -> REG_TEMP: b4 = b5 = 0; b7, b6 valid (1/4 degrees resolution) 
14  b6 = 1, b5 = 0 -> REG_TEMP: b4 = 0; b7, b6, b5 valid (1/8 degrees resolution) 
15  b5 = 1, b6 = 1 -> REG_TEMP: b7, b6, b5, b4 valid (1/16 degrees resolution) 
16  ''' 
17  import smbus 
18   
19  REG_TEMP = 0x00    # Temperature register 
20  REG_CONFIG = 0x01  # Configuration register 
21  _bus = smbus.SMBus(1)  # RPi revision 2 (0 for revision 1) 
22   
23 -def init(i2c_address = 0x48, resolution = 3):
24 global _i2c_address 25 _i2c_address = i2c_address 26 if resolution == 0: # 1/2 degress 27 config = 0x00 28 elif resolution == 1: # 1/4 degrees 29 config = 0x20 30 elif resolution == 2: # 1/8 degrees 31 config = 0x40 32 elif resolution == 3: # 1/16 degrees 33 config = 0x60 34 _bus.write_byte_data(i2c_address, REG_CONFIG, config)
35
36 -def getTemperature():
37 data = _bus.read_word_data(_i2c_address, REG_TEMP) 38 highbyte = (data >> 8) & 0xFF 39 lowbyte = data & 0xFF 40 (lowbyte, highbyte) = (highbyte, lowbyte) # swap (smbus uses little endian) 41 sign = 1 42 if highbyte & 0x80 == 0x80: # sign bit set 43 sign = -1 44 temp = highbyte & 0x7F # clear sign bit 45 lowbyte = lowbyte >> 4 # shift fraction bits to right 46 fraction = lowbyte / 16.0 47 temp = sign * (temp + fraction) 48 return int((temp * 10)) / 10 # rounded to 1 decimal
49