forked from Seeed-Studio/Grove_SHT31_Temp_Humi_Sensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SHT31.cpp
109 lines (86 loc) · 1.91 KB
/
SHT31.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "SHT31.h"
SHT31::SHT31() {
}
boolean SHT31::begin(uint8_t i2caddr) {
Wire.begin();
_i2caddr = i2caddr;
reset();
//return (readStatus() == 0x40);
return true;
}
//boolean S == Scale. True == Farenheit; False == Celcius
float SHT31::getTemperature(bool S) {
if (! getTempHum()) return NAN;
if (S == true) {
return convertCtoF(temp);
}
return temp;
}
float SHT31::convertCtoF(float c) {
return c * 9 / 5 + 32;
}
float SHT31::getHumidity(void) {
if (! getTempHum()) return NAN;
return humidity;
}
uint16_t SHT31::readStatus(void) {
}
void SHT31::reset(void) {
writeCommand(SHT31_SOFTRESET);
delay(10);
}
void SHT31::heater(boolean h) {
if (h)
writeCommand(SHT31_HEATEREN);
else
writeCommand(SHT31_HEATERDIS);
}
uint8_t SHT31::crc8(const uint8_t *data, int len) {
const uint8_t POLYNOMIAL(0x31);
uint8_t crc(0xFF);
for ( int j = len; j; --j ) {
crc ^= *data++;
for ( int i = 8; i; --i ) {
crc = ( crc & 0x80 )
? (crc << 1) ^ POLYNOMIAL
: (crc << 1);
}
}
return crc;
}
boolean SHT31::getTempHum(void) {
uint8_t readbuffer[6];
writeCommand(SHT31_MEAS_HIGHREP);
delay(50);
Wire.requestFrom(_i2caddr, (uint8_t)6);
if (Wire.available() != 6)
return false;
for (uint8_t i=0; i<6; i++) {
readbuffer[i] = Wire.read();
}
uint16_t ST, SRH;
ST = readbuffer[0];
ST <<= 8;
ST |= readbuffer[1];
if (readbuffer[2] != crc8(readbuffer, 2)) return false;
SRH = readbuffer[3];
SRH <<= 8;
SRH |= readbuffer[4];
if (readbuffer[5] != crc8(readbuffer+3, 2)) return false;
double stemp = ST;
stemp *= 175;
stemp /= 0xffff;
stemp = -45 + stemp;
temp = stemp;
double shum = SRH;
shum *= 100;
shum /= 0xFFFF;
humidity = shum;
return true;
}
void SHT31::writeCommand(uint16_t cmd) {
Wire.beginTransmission(_i2caddr);
Wire.write(cmd >> 8);
Wire.write(cmd & 0xFF);
Wire.endTransmission();
}