-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinySHT2x.cpp
148 lines (112 loc) · 2.43 KB
/
tinySHT2x.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
//
// FILE: tinySHT2x.cpp
// AUTHOR: Rob Tillaart, Viktor Balint
// VERSION: 0.2.0
// DATE: 2021-09-27
// PURPOSE: Arduino library for the SHT2x temperature and humidity sensor optimized for AVR tiny
// URL: https://github.com/RobTillaart/tinySHT2x
#include "tinySHT2x.h"
#define SHT2x_GET_TEMPERATURE_NO_HOLD 0xF3
#define SHT2x_GET_HUMIDITY_NO_HOLD 0xF5
#define SHT2x_SOFT_RESET 0xFE
#define SHT2x_ADDRESS 0x40
tinySHT2x::tinySHT2x(TwoWire *wire)
{
_wire = wire;
}
bool tinySHT2x::begin()
{
return isConnected();
}
bool tinySHT2x::isConnected()
{
_wire->beginTransmission(SHT2x_ADDRESS);
return (_wire->endTransmission() == 0);
}
bool tinySHT2x::reset()
{
return writeCmd(SHT2x_SOFT_RESET);
}
///////////////////////////////////
//
// ASYNC INTERFACE
//
void tinySHT2x::requestTemperature()
{
writeCmd(SHT2x_GET_TEMPERATURE_NO_HOLD);
}
float tinySHT2x::readTemperature()
{
uint8_t buffer[3];
uint16_t raw;
if (readBytes(3, (uint8_t*) &buffer[0], 90) == false)
{
return TINY_SHT2x_NO_VALUE;
}
raw = buffer[0] << 8;
raw += buffer[1];
raw &= 0xFFFC;
return -46.85 + (175.72 / 65536.0) * raw;
}
void tinySHT2x::requestHumidity()
{
writeCmd(SHT2x_GET_HUMIDITY_NO_HOLD);
}
float tinySHT2x::readHumidity()
{
uint8_t buffer[3];
uint16_t raw;
if (readBytes(3, (uint8_t*) &buffer[0], 30) == false)
{
return TINY_SHT2x_NO_VALUE;
}
raw = buffer[0] << 8;
raw += buffer[1];
raw &= 0xFFFC;
return -6.0 + (125.0 / 65536.0) * raw;
}
///////////////////////////////////
//
// SYNC INTERFACE
//
float tinySHT2x::getTemperature(uint8_t del)
{
requestTemperature();
delay(del);
return readTemperature();
}
float tinySHT2x::getHumidity(uint8_t del)
{
requestHumidity();
delay(del);
return readHumidity();
}
//////////////////////////////////////////////////////////
//
// PRIVATE
//
bool tinySHT2x::writeCmd(uint8_t cmd)
{
_wire->beginTransmission(SHT2x_ADDRESS);
_wire->write(cmd);
return (_wire->endTransmission() == 0);
}
bool tinySHT2x::readBytes(uint8_t n, uint8_t * val, uint8_t maxDuration)
{
_wire->requestFrom((uint8_t)SHT2x_ADDRESS, (uint8_t) n);
uint32_t start = millis();
while (_wire->available() < n)
{
if (millis() - start > maxDuration)
{
return false;
}
yield();
}
for (uint8_t i = 0; i < n; i++)
{
val[i] = _wire->read();
}
return true;
}
// -- END OF FILE --