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
148
149
#![no_std]
#![deny(warnings, missing_docs)]
use embedded_hal::blocking::{delay, i2c};
const DEVICE_I2C_ADDR: u8 = 0x5c;
#[derive(Debug)]
pub enum Error {
WriteError,
ReadError,
SensorError,
}
#[derive(Debug)]
pub struct Measurement {
pub temperature: f32,
pub humidity: f32,
}
pub struct Am2320<I2C, Delay> {
device: I2C,
delay: Delay,
}
#[inline(always)]
fn crc16(data: &[u8]) -> u16 {
let mut crc: u16 = 0xFFFF;
for e in data.iter() {
crc ^= u16::from(*e);
for _ in 0..8 {
if crc & 0x0001 == 0x0001 {
crc >>= 1;
crc ^= 0xA001;
} else {
crc >>= 1;
}
}
}
crc
}
impl<I2C, Delay, E> Am2320<I2C, Delay>
where
I2C: i2c::Read<Error = E> + i2c::Write<Error = E>,
Delay: delay::DelayUs<u16>,
{
pub fn new(device: I2C, delay: Delay) -> Self {
Self { device, delay }
}
pub fn read(&mut self) -> Result<Measurement, Error> {
let _ = self.device.write(DEVICE_I2C_ADDR, &[0x00]);
self.delay.delay_us(900);
self.device
.write(DEVICE_I2C_ADDR, &[0x03, 0x00, 0x04])
.map_err(|_| Error::WriteError)?;
self.delay.delay_us(1600);
let mut data = [0; 8];
self.device
.read(DEVICE_I2C_ADDR, &mut data)
.map_err(|_| Error::ReadError)?;
if data[0] != 0x03 || data[1] != 0x04 {
return Err(Error::SensorError);
}
let crc = crc16(&data[0..6]);
if crc != u16::from_le_bytes([data[6], data[7]]) {
return Err(Error::SensorError);
}
let mut temperature = i16::from_be_bytes([data[4] & 0b0111_1111, data[5]]);
if data[4] & 0b1000_0000 != 0 {
temperature = -temperature;
}
let humidity = u16::from_be_bytes([data[2], data[3]]);
Ok(Measurement {
temperature: f32::from(temperature) / 10.0,
humidity: f32::from(humidity) / 10.0,
})
}
}
#[test]
fn test_crc16() {
assert_eq!(crc16(&[]), 0xFFFF);
assert_eq!(crc16(&[0x03, 0x04, 0x02, 0x36, 0x0, 0xDB]), 0x0550);
}