-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patham2302.hpp
72 lines (63 loc) · 2.16 KB
/
am2302.hpp
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
#include <bitset>
namespace oscarIO {
namespace am2302 {
namespace detail {
struct packet {
unsigned int temp;
bool tempSign;
unsigned int rh;
};
template<std::size_t N>
void reverse(std::bitset<N> &b) {
for (std::size_t i = 0; i < N / 2; ++i) {
bool t = b[i];
b[i] = b[N - i - 1];
b[N - i - 1] = t;
}
}
}
auto measure(hwlib::pin_in_out& sensor) {
auto waitTillState = [&](bool state) {
for (int i; i < 1000000; i++) {
if (sensor.read() == state) {
return true;
}
}
return false;
};
auto getBit = [&]() {
waitTillState(true);
auto duration = hwlib::now_us(); // get current time
waitTillState(false);
duration = hwlib::now_us() - duration; // Calculate time
return duration > 40;
};
std::bitset<40> receivebufferb = 0;
sensor.direction_set_output();
sensor.write(false);
hwlib::wait_ms(1);
sensor.write(true); // Host pull up
hwlib::wait_us(40);
sensor.direction_set_input();
hwlib::wait_us(40);
waitTillState(true);
waitTillState(false);
waitTillState(true);
waitTillState(false);
for (int i = 0; i < 40; i++) {
receivebufferb[i] = getBit();
}
std::bitset<16> rh = 0;
for (int i = 0; i < 16; i++) {
rh[i] = receivebufferb[i];
}
detail::reverse(rh);
std::bitset<15> temp = 0;
for (int i = 17; i < 32; i++) {
temp[i - 17] = receivebufferb[i];
}
detail::reverse(temp);
return detail::packet{static_cast<unsigned int>(temp.to_ulong()),receivebufferb[16], static_cast<unsigned int>(rh.to_ulong())};
}
}
}