1
+ #!/usr/bin/python
2
+
3
+ import time
4
+ from Adafruit_I2C import Adafruit_I2C
5
+
6
+ # ===========================================================================
7
+ # HTU21D Class
8
+ # ===========================================================================
9
+
10
+ class HTU21D :
11
+ i2c = None
12
+
13
+ # HTU21D Address
14
+ address = 0x40
15
+
16
+ # Commands
17
+ TRIGGER_TEMP_MEASURE_HOLD = 0xE3
18
+ TRIGGER_HUMD_MEASURE_HOLD = 0xE5
19
+ READ_USER_REG = 0xE7
20
+
21
+ # Constructor
22
+ def __init__ (self ):
23
+ self .i2c = Adafruit_I2C (self .address )
24
+
25
+ def readUserRegister (self ):
26
+ # Read a byte
27
+ value = self .i2c .readU8 (self .READ_USER_REG )
28
+
29
+ return value
30
+
31
+ def readTemperatureData (self ):
32
+ # value[0], value[1]: Raw temperature data
33
+ # value[2]: CRC
34
+ value = self .i2c .readList (self .TRIGGER_TEMP_MEASURE_HOLD , 3 )
35
+
36
+ if not self .crc8check (value ):
37
+ return - 255
38
+
39
+ rawTempData = ( value [0 ] << 8 ) + value [1 ]
40
+
41
+ # Zero out the status bits but keep them in place
42
+ rawTempData = rawTempData & 0xFFFC ;
43
+
44
+ # Calculate the actual temperature
45
+ actualTemp = - 46.85 + (175.72 * rawTempData / 65536 )
46
+
47
+ return actualTemp
48
+
49
+ def readHumidityData (self ):
50
+ # value[0], value[1]: Raw relative humidity data
51
+ # value[2]: CRC
52
+ value = self .i2c .readList (self .TRIGGER_HUMD_MEASURE_HOLD , 3 )
53
+
54
+ if not self .crc8check (value ):
55
+ return - 255
56
+
57
+ rawRHData = ( value [0 ] << 8 ) + value [1 ]
58
+
59
+ # Zero out the status bits but keep them in place
60
+ rawRHData = rawRHData & 0xFFFC ;
61
+
62
+ # Calculate the actual RH
63
+ actualRH = - 6 + (125.0 * rawRHData / 65536 )
64
+
65
+ return actualRH
66
+
67
+ def crc8check (self , value ):
68
+ remainder = ( ( value [0 ] << 8 ) + value [1 ] ) << 8
69
+ remainder |= value [2 ]
70
+
71
+ # POLYNOMIAL = 0x0131 = x^8 + x^5 + x^4 + 1
72
+ # divsor = 0x988000 is the 0x0131 polynomial shifted to farthest left of three bytes
73
+ divsor = 0x988000
74
+
75
+ for i in range (0 , 16 ):
76
+ if ( remainder & 1 << (23 - i ) ):
77
+ remainder ^= divsor
78
+
79
+ divsor = divsor >> 1
80
+
81
+ if remainder == 0 :
82
+ return True
83
+ else :
84
+ return False
85
+
0 commit comments