hdc302x 0.4.1

An embedded driver for the HDC302x(-Q1) low-power humidity and temperature digital sensor
Documentation
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::hw_def::*;
use crate::types::*;

use cfg_if::cfg_if;

#[cfg(feature = "crc")]
use crc::{Crc, CRC_8_NRSC_5};

#[cfg(feature = "defmt")]
use defmt::{trace, warn};
#[cfg(feature = "log")]
use log::{trace, warn};
#[cfg(not(any(feature = "defmt", feature = "log")))]
macro_rules! trace {
    ($($arg:tt)*) => {};
}
#[cfg(not(any(feature = "defmt", feature = "log")))]
macro_rules! warn {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "crc")]
const CRC: crc::Crc<u8> = Crc::<u8>::new(&CRC_8_NRSC_5);

impl<I2C, Delay> Hdc302x<I2C, Delay> {
    /// Create a new HDC302x driver instance
    pub fn new(i2c: I2C, delay: Delay, i2c_addr: I2cAddr) -> Self {
        Self { i2c, delay, i2c_addr }
    }
}

#[cfg(feature = "blocking")]
impl<I2C, Delay, E> Hdc302x<I2C, Delay>
where
    I2C: embedded_hal::i2c::I2c<Error = E>,
    Delay: embedded_hal::delay::DelayNs,
{
    fn cmd_delay_read(&mut self, cmd_bytes: &[u8; 2], delay_us: Option<u32>, read_vals: &mut [u16]) -> Result<(), Error<E>> {
        let num_vals = read_vals.len();
        // We are heapless, so have to have an upper bound
        assert!(num_vals <= 2);

        if read_vals.is_empty() {
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), cmd_bytes) {
                return Err(Error::I2c(i2c_err));
            }
        } else {
            let mut read_buf = [0u8; 6];
            let read_buf_slice = &mut read_buf[0..(3 * num_vals)];
            trace!("hdc302x::cmd_delay_read(): read_buf_slice.len()={}", read_buf_slice.len());
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), cmd_bytes) {
                return Err(Error::I2c(i2c_err));
            }
            if let Some(delay_us) = delay_us {
                self.delay.delay_us(delay_us);
            }
            if let Err(i2c_err) = self.i2c.read(self.i2c_addr.as_u8(), read_buf_slice) {
                return Err(Error::I2c(i2c_err));
            }
            // TODO: consider whether to retry around this failure
            for ii in 0..num_vals {
                let read_word = &read_buf[ii*3..=ii*3+1];
                cfg_if! {
                    if #[cfg(feature = "crc")] {
                        let read_crc = &read_buf[ii*3+2];
                        let crc_expect = CRC.checksum(read_word);
                        if *read_crc != crc_expect {
                            warn!("hdc302x::cmd_delay_read(): crc mismatch word {}/{}: read_buf={:?}, read_word={:?}, read_crc={}, crc_expect={}",
                                ii,
                                num_vals,
                                read_buf,
                                read_word,
                                read_crc,
                                crc_expect);
                            return Err(Error::CrcMismatch);
                        }
                    }
                }
                read_vals[ii] = (read_word[0] as u16) << 8 | read_word[1] as u16;
            }
        }
        Ok(())
    }

    /// Trigger a one-shot measurement and return the raw sample pair
    pub fn one_shot(&mut self, low_power_mode: LowPowerMode) -> Result<RawDatum, Error<E>> {
        let cmd_bytes = start_sampling_command(SampleRate::OneShot, low_power_mode.clone()).to_be_bytes();
        let delay_us = 100 + match low_power_mode {
            LowPowerMode::LPM0 => 12_500,
            LowPowerMode::LPM1 =>  7_500,
            LowPowerMode::LPM2 =>  5_000,
            LowPowerMode::LPM3 =>  3_700,
        };
        let mut read_buf = [0u16; 2];
        self.cmd_delay_read(&cmd_bytes, Some(delay_us), &mut read_buf)?;
        Ok(RawDatum::TempAndRelHumid(RawTempAndRelHumid {
            temperature: read_buf[0],
            humidity: read_buf[1],
        }))
    }

    /// Enter auto mode (continuous self-timed sampling)
    pub fn auto_start(&mut self, sample_rate: SampleRate, low_power_mode: LowPowerMode) -> Result<(), Error<E>> {
        let cmd_bytes = start_sampling_command(sample_rate, low_power_mode).to_be_bytes();
        self.cmd_delay_read(&cmd_bytes, None, &mut [0u16; 0])?;
        Ok(())
    }

    /// exit auto mode and return to sleep
    pub fn auto_stop(&mut self) -> Result<(), Error<E>> {
        self.cmd_delay_read(&Command::AutoExit.as_be_bytes(), None, &mut [0u16; 0])?;
        Ok(())
    }

    /// read most recent temperature and relative humidity from auto mode
    pub fn auto_read(&mut self, target: AutoReadTarget) -> Result<RawDatum, Error<E>> {
        let cmd_bytes = match target {
            AutoReadTarget::LastTempAndRelHumid => Command::AutoReadTempAndRelHumid,
            AutoReadTarget::MinTemp => Command::AutoReadMinTemp,
            AutoReadTarget::MaxTemp => Command::AutoReadMaxTemp,
            AutoReadTarget::MinRelHumid => Command::AutoReadMinRelHumid,
            AutoReadTarget::MaxRelHumid => Command::AutoReadMaxRelHumid,
        }.as_be_bytes();

        let mut read_buf = [0u16; 2];
        let read_buf_slice = match target {
            AutoReadTarget::LastTempAndRelHumid => &mut read_buf[..2],
            AutoReadTarget::MinTemp => &mut read_buf[..1],
            AutoReadTarget::MaxTemp => &mut read_buf[..1],
            AutoReadTarget::MinRelHumid => &mut read_buf[..1],
            AutoReadTarget::MaxRelHumid => &mut read_buf[..1],
        };

        self.cmd_delay_read(&cmd_bytes, None, read_buf_slice)?;

        Ok(match target {
            AutoReadTarget::LastTempAndRelHumid => RawDatum::TempAndRelHumid(RawTempAndRelHumid {
                temperature: read_buf[0],
                humidity: read_buf[1],
            }),
            AutoReadTarget::MinTemp => RawDatum::MinTemp(read_buf[0]),
            AutoReadTarget::MaxTemp => RawDatum::MaxTemp(read_buf[0]),
            AutoReadTarget::MinRelHumid => RawDatum::MinRelHumid(read_buf[0]),
            AutoReadTarget::MaxRelHumid => RawDatum::MaxRelHumid(read_buf[0]),
        })
    }

    /// Condensation heater
    pub fn heater(&mut self, heater_level: HeaterLevel) -> Result<(), Error<E>> {
        self.cmd_delay_read(&Command::HeaterDisable.as_be_bytes(), None, &mut [0u16; 0])?;

        if let Some(setting) = heater_level.setting() {
            let mut cmd_bytes = [0u8; 4];
            cmd_bytes[0..2].copy_from_slice(&Command::HeaterConfig.as_be_bytes());
            cmd_bytes[2..4].copy_from_slice(&setting.to_be_bytes());
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), &cmd_bytes) {
                return Err(Error::I2c(i2c_err));
            }
            self.cmd_delay_read(&Command::HeaterEnable.as_be_bytes(), None, &mut [0u16; 0])?;
        }
        Ok(())
    }

    /// Read and optionally clear status bits
    pub fn read_status(&mut self, clear: bool) -> Result<StatusBits, Error<E>> {
        let mut read_buf = [0u16; 1];
        self.cmd_delay_read(&Command::StatusRead.as_be_bytes(), None, &mut read_buf)?;
        if clear {
            self.cmd_delay_read(&Command::StatusClear.as_be_bytes(), None, &mut [0u16; 0])?;
        }

        Ok(StatusBits::from(read_buf[0]))
    }

    /// Read the NIST-tracable serial number
    pub fn read_serial_number(&mut self) -> Result<SerialNumber, Error<E>> {
        let mut temp_u16 = [0u16; 1];
        let mut bytes= [0u8; 6];
        self.cmd_delay_read(&Command::SerialID54.as_be_bytes(), None, &mut temp_u16)?;
        bytes[5] = (temp_u16[0] >> 8) as u8;
        bytes[4] = temp_u16[0] as u8;
        self.cmd_delay_read(&Command::SerialID32.as_be_bytes(), None, &mut temp_u16)?;
        bytes[3] = (temp_u16[0] >> 8) as u8;
        bytes[2] = temp_u16[0] as u8;
        self.cmd_delay_read(&Command::SerialID10.as_be_bytes(), None, &mut temp_u16)?;
        bytes[1] = (temp_u16[0] >> 8) as u8;
        bytes[0] = temp_u16[0] as u8;
        Ok(SerialNumber(bytes))
    }

    /// Read the NIST-tracable manufacturer ID
    pub fn read_manufacturer_id(&mut self) -> Result<ManufacturerId, Error<E>> {
        let mut read_buf = [0u16; 1];
        self.cmd_delay_read(&Command::ManufacturerID.as_be_bytes(), None, &mut read_buf)?;
        Ok(ManufacturerId::from(read_buf[0]))
    }

    /// software reset
    pub fn software_reset(&mut self) -> Result<(), Error<E>> {
        self.cmd_delay_read(&Command::SoftReset.as_be_bytes(), None, &mut [0u16; 0])?;
        Ok(())
    }

    // TODO: Support Alerting
    // Command::WriteSetLowAlert,
    // Command::WriteSetHighAlert,
    // Command::WriteClearLowAlert,
    // Command::WriteClearHighAlert,
    // Command::AlertToNV,

    // Command::ReadSetLowAlert,
    // Command::ReadSetHighAlert,
    // Command::ReadClearLowAlert,
    // Command::ReadClearHighAlert,

    // TODO: Support non-volatile offset
    // Command::NVOffset,

    // TODO: Support reset state
    // Command::ResetState,
}

// TODO: consider adding type state pattern around the state of the device.  When we start a
// one-shot, don't do things other than read the result until that happens.  When in auto mode,
// don't do one-shot samples.  When sleeping (not in one-shot or auto mode), don't read auto mode
// results.
#[cfg(feature = "async")]
impl<I2C, Delay, E> Hdc302x<I2C, Delay>
where
    I2C: embedded_hal_async::i2c::I2c<Error = E>,
    Delay: embedded_hal_async::delay::DelayNs,
{
    async fn cmd_delay_read_async(&mut self, cmd_bytes: &[u8; 2], delay_us: Option<u32>, read_vals: &mut [u16]) -> Result<(), Error<E>> {
        let num_vals = read_vals.len();
        // We are heapless, so have to have an upper bound
        assert!(num_vals <= 2);

        if read_vals.is_empty() {
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), cmd_bytes).await {
                return Err(Error::I2c(i2c_err));
            }
        } else {
            let mut read_buf = [0u8; 6];
            let read_buf_slice = &mut read_buf[0..(3 * num_vals)];
            trace!("hdc302x::cmd_delayread_async(): read_buf_slice.len()={}", read_buf_slice.len());
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), cmd_bytes).await {
                return Err(Error::I2c(i2c_err));
            }
            if let Some(delay_us) = delay_us {
                self.delay.delay_us(delay_us).await;
            }
            if let Err(i2c_err) = self.i2c.read(self.i2c_addr.as_u8(), read_buf_slice).await {
                return Err(Error::I2c(i2c_err));
            }
            // TODO: consider whether to retry around this failure
            for ii in 0..num_vals {
                let read_word = &read_buf[ii*3..=ii*3+1];
                cfg_if! {
                    if #[cfg(feature = "crc")] {
                        let read_crc = &read_buf[ii*3+2];
                        let crc_expect = CRC.checksum(read_word);
                        if *read_crc != crc_expect {
                            warn!("hdc302x::cmd_delay_read_async(): crc mismatch word {}/{}: read_buf={:?}, read_word={:?}, read_crc={}, crc_expect={}",
                                ii,
                                num_vals,
                                read_buf,
                                read_word,
                                read_crc,
                                crc_expect);
                            return Err(Error::CrcMismatch);
                        }
                    }
                }
                read_vals[ii] = (read_word[0] as u16) << 8 | read_word[1] as u16;
            }
        }
        Ok(())
    }

    /// Trigger a one-shot measurement and return the raw sample pair
    pub async fn one_shot_async(&mut self, low_power_mode: LowPowerMode) -> Result<RawDatum, Error<E>> {
        let cmd_bytes = start_sampling_command(SampleRate::OneShot, low_power_mode.clone()).to_be_bytes();
        let delay_us = 100 + match low_power_mode {
            LowPowerMode::LPM0 => 12_500,
            LowPowerMode::LPM1 =>  7_500,
            LowPowerMode::LPM2 =>  5_000,
            LowPowerMode::LPM3 =>  3_700,
        };
        let mut read_buf = [0u16; 2];
        self.cmd_delay_read_async(&cmd_bytes, Some(delay_us), &mut read_buf).await?;
        Ok(RawDatum::TempAndRelHumid(RawTempAndRelHumid {
            temperature: read_buf[0],
            humidity: read_buf[1],
        }))
    }

    /// Enter auto mode (continuous self-timed sampling)
    pub async fn auto_start_async(&mut self, sample_rate: SampleRate, low_power_mode: LowPowerMode) -> Result<(), Error<E>> {
        let cmd_bytes = start_sampling_command(sample_rate, low_power_mode).to_be_bytes();
        self.cmd_delay_read_async(&cmd_bytes, None, &mut [0u16; 0]).await?;
        Ok(())
    }

    /// exit auto mode and return to sleep
    pub async fn auto_stop_async(&mut self) -> Result<(), Error<E>> {
        self.cmd_delay_read_async(&Command::AutoExit.as_be_bytes(), None, &mut [0u16; 0]).await?;
        Ok(())
    }

    /// read most recent temperature and relative humidity from auto mode
    pub async fn auto_read_async(&mut self, target: AutoReadTarget) -> Result<RawDatum, Error<E>> {
        let cmd_bytes = match target {
            AutoReadTarget::LastTempAndRelHumid => Command::AutoReadTempAndRelHumid,
            AutoReadTarget::MinTemp => Command::AutoReadMinTemp,
            AutoReadTarget::MaxTemp => Command::AutoReadMaxTemp,
            AutoReadTarget::MinRelHumid => Command::AutoReadMinRelHumid,
            AutoReadTarget::MaxRelHumid => Command::AutoReadMaxRelHumid,
        }.as_be_bytes();

        let mut read_buf = [0u16; 2];
        let read_buf_slice = match target {
            AutoReadTarget::LastTempAndRelHumid => &mut read_buf[..2],
            AutoReadTarget::MinTemp => &mut read_buf[..1],
            AutoReadTarget::MaxTemp => &mut read_buf[..1],
            AutoReadTarget::MinRelHumid => &mut read_buf[..1],
            AutoReadTarget::MaxRelHumid => &mut read_buf[..1],
        };

        self.cmd_delay_read_async(&cmd_bytes, None, read_buf_slice).await?;

        Ok(match target {
            AutoReadTarget::LastTempAndRelHumid => RawDatum::TempAndRelHumid(RawTempAndRelHumid {
                temperature: read_buf[0],
                humidity: read_buf[1],
            }),
            AutoReadTarget::MinTemp => RawDatum::MinTemp(read_buf[0]),
            AutoReadTarget::MaxTemp => RawDatum::MaxTemp(read_buf[0]),
            AutoReadTarget::MinRelHumid => RawDatum::MinRelHumid(read_buf[0]),
            AutoReadTarget::MaxRelHumid => RawDatum::MaxRelHumid(read_buf[0]),
        })
    }

    /// Condensation heater
    pub async fn heater_async(&mut self, heater_level: HeaterLevel) -> Result<(), Error<E>> {
        self.cmd_delay_read_async(&Command::HeaterDisable.as_be_bytes(), None, &mut [0u16; 0]).await?;

        if let Some(setting) = heater_level.setting() {
            let mut cmd_bytes = [0u8; 4];
            cmd_bytes[0..2].copy_from_slice(&Command::HeaterConfig.as_be_bytes());
            cmd_bytes[2..4].copy_from_slice(&setting.to_be_bytes());
            if let Err(i2c_err) = self.i2c.write(self.i2c_addr.as_u8(), &cmd_bytes).await {
                return Err(Error::I2c(i2c_err));
            }
            self.cmd_delay_read_async(&Command::HeaterEnable.as_be_bytes(), None, &mut [0u16; 0]).await?;
        }
        Ok(())
    }

    /// Read and optionally clear status bits
    pub async fn read_status_async(&mut self, clear: bool) -> Result<StatusBits, Error<E>> {
        let mut read_buf = [0u16; 1];
        self.cmd_delay_read_async(&Command::StatusRead.as_be_bytes(), None, &mut read_buf).await?;
        if clear {
            self.cmd_delay_read_async(&Command::StatusClear.as_be_bytes(), None, &mut [0u16; 0]).await?;
        }

        Ok(StatusBits::from(read_buf[0]))
    }

    /// Read the NIST-tracable serial number
    pub async fn read_serial_number_async(&mut self) -> Result<SerialNumber, Error<E>> {
        let mut temp_u16 = [0u16; 1];
        let mut bytes= [0u8; 6];
        self.cmd_delay_read_async(&Command::SerialID54.as_be_bytes(), None, &mut temp_u16).await?;
        bytes[5] = (temp_u16[0] >> 8) as u8;
        bytes[4] = temp_u16[0] as u8;
        self.cmd_delay_read_async(&Command::SerialID32.as_be_bytes(), None, &mut temp_u16).await?;
        bytes[3] = (temp_u16[0] >> 8) as u8;
        bytes[2] = temp_u16[0] as u8;
        self.cmd_delay_read_async(&Command::SerialID10.as_be_bytes(), None, &mut temp_u16).await?;
        bytes[1] = (temp_u16[0] >> 8) as u8;
        bytes[0] = temp_u16[0] as u8;
        Ok(SerialNumber(bytes))
    }

    /// Read the NIST-tracable manufacturer ID
    pub async fn read_manufacturer_id_async(&mut self) -> Result<ManufacturerId, Error<E>> {
        let mut read_buf = [0u16; 1];
        self.cmd_delay_read_async(&Command::ManufacturerID.as_be_bytes(), None, &mut read_buf).await?;
        Ok(ManufacturerId::from(read_buf[0]))
    }

    /// software reset
    pub async fn software_reset_async(&mut self) -> Result<(), Error<E>> {
        self.cmd_delay_read_async(&Command::SoftReset.as_be_bytes(), None, &mut [0u16; 0]).await?;
        Ok(())
    }

    // TODO: Support Alerting
    // Command::WriteSetLowAlert,
    // Command::WriteSetHighAlert,
    // Command::WriteClearLowAlert,
    // Command::WriteClearHighAlert,
    // Command::AlertToNV,

    // Command::ReadSetLowAlert,
    // Command::ReadSetHighAlert,
    // Command::ReadClearLowAlert,
    // Command::ReadClearHighAlert,

    // TODO: Support non-volatile offset
    // Command::NVOffset,

    // TODO: Support reset state
    // Command::ResetState,
}