ph_sht4x_hts/lib.rs
1#![no_std]
2#![forbid(unsafe_code)]
3#![deny(missing_docs)]
4#![doc = include_str!("../README.md")]
5
6use embedded_hal_async::{delay::DelayNs, i2c::I2c};
7
8/// The 7-bit I2C address an SHT4x answers on.
9///
10/// Fixed by position 7 of the part number under `SHT4X-PART-NOM-001`, and
11/// recorded as `SHT4X-I2C-ADDR-001`. It is **not** a function of the sensor
12/// model: an SHT40 ships at all three addresses and an SHT43 at two, so read
13/// this off the part number you ordered rather than inferring it from whether
14/// the part is an SHT40, SHT41, SHT43, or SHT45.
15///
16/// The variants are named for the part-number position they correspond to, so
17/// the lookup is direct: `SHT40-BD1B-R2` has `B` at position 7 and therefore
18/// answers on [`Address::B`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Address {
21 /// Part-number position 7 `A`: 7-bit address `0x44`.
22 A,
23 /// Part-number position 7 `B`: 7-bit address `0x45`.
24 B,
25 /// Part-number position 7 `C`: 7-bit address `0x46`.
26 C,
27}
28
29impl Address {
30 /// The 7-bit address as it appears on the bus.
31 #[must_use]
32 pub const fn bits(self) -> u8 {
33 match self {
34 Self::A => 0x44,
35 Self::B => 0x45,
36 Self::C => 0x46,
37 }
38 }
39}
40
41const SERIAL_NUMBER_COMMAND: u8 = 0x89;
42// `SHT4X-SN-WAIT-001` adopts the current Sensirion reference driver's
43// conservative wait. The datasheet does not publish a serial completion bound,
44// so this is not a claimed device-busy frontier.
45const SERIAL_NUMBER_DURATION_US: u32 = 10_000;
46// Every response this driver reads is the same shape: two big-endian 16-bit
47// words, each followed by its CRC-8 byte.
48const RESPONSE_LEN: usize = 6;
49const SOFT_RESET_COMMAND: u8 = 0x94;
50const SOFT_RESET_DURATION_US: u32 = 1_000;
51// `tHeater` includes the high-repeatability measurement performed before the
52// heater is switched off, per `SHT4X-HEAT-TIME-001`.
53const HEATER_LONG_DURATION_US: u32 = 1_100_000;
54const HEATER_SHORT_DURATION_US: u32 = 110_000;
55const MEASUREMENT_HIGH_DURATION_US: u32 = 8_300;
56const MEASUREMENT_MEDIUM_DURATION_US: u32 = 4_500;
57const MEASUREMENT_LOW_DURATION_US: u32 = 1_600;
58
59/// Errors returned by the SHT4x driver.
60#[derive(Debug, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum Error<E> {
63 /// The device or bus rejected the transfer for a reason other than NACK.
64 I2c(E),
65 /// The device was not ready or otherwise did not acknowledge the transfer.
66 ///
67 /// Per `SHT45-I2C-XFER-001` the device NACKs a read header while it is
68 /// busy, so this is the expected result before the documented measurement
69 /// or heater frontier. The datasheet defines no corresponding behavior for
70 /// the serial reference-wait interval. The driver does not retry.
71 NoAcknowledge(E),
72 /// One of the two response words failed its CRC check.
73 ///
74 /// The driver does not retry a failed CRC, per `SHT45-CRC-001`.
75 Crc {
76 /// Which of the two 16-bit response words failed: `0` or `1`.
77 ///
78 /// For a measurement or heater pulse, word `0` is temperature and word
79 /// `1` is relative humidity. For a serial-number read they are the
80 /// high and low halves of the serial in transmission order.
81 word: usize,
82 /// The CRC-8 computed over the received word.
83 expected: u8,
84 /// The CRC-8 byte the device sent.
85 actual: u8,
86 },
87}
88
89impl<E: core::fmt::Display> core::fmt::Display for Error<E> {
90 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
91 match self {
92 Self::I2c(error) => write!(f, "I2C transfer failed: {error}"),
93 Self::NoAcknowledge(error) => {
94 write!(f, "device did not acknowledge the transfer: {error}")
95 }
96 Self::Crc {
97 word,
98 expected,
99 actual,
100 } => write!(
101 f,
102 "CRC mismatch on response word {word}: computed {expected:#04x}, received {actual:#04x}"
103 ),
104 }
105 }
106}
107
108impl<E> core::error::Error for Error<E>
109where
110 E: core::error::Error + 'static,
111{
112 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
113 match self {
114 Self::I2c(error) | Self::NoAcknowledge(error) => Some(error),
115 Self::Crc { .. } => None,
116 }
117 }
118}
119
120/// Measurement repeatability supported by the SHT4x.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum Repeatability {
123 /// High repeatability: maximum measurement duration 8.3 ms.
124 High,
125 /// Medium repeatability: maximum measurement duration 4.5 ms.
126 Medium,
127 /// Low repeatability: maximum measurement duration 1.6 ms.
128 Low,
129}
130
131/// Heater power selected for one bounded heater pulse.
132///
133/// Each variant selects one of the three heater commands available for the
134/// requested duration, per `SHT45-HEAT-PWR-001`.
135///
136/// The wattages below are the datasheet's **typical** values at **VDD = 3.3 V**.
137/// They are not a delivered or guaranteed figure: a typical value is not a
138/// bound, and the figures are qualified to that one supply voltage. Treat them
139/// as naming which documented level you selected, not as how much energy the
140/// device will dissipate.
141///
142/// The driver selects the command byte. It does not meter delivered energy or
143/// enforce the operating limits of `SHT4X-HEAT-USE-001`, including the
144/// less-than-10-percent duty cycle. Those remain caller responsibilities.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum HeaterPower {
147 /// Highest level, typically 200 mW at 3.3 V: `0x39` when long, `0x32` when short.
148 High,
149 /// Middle level, typically 110 mW at 3.3 V: `0x2F` when long, `0x24` when short.
150 Medium,
151 /// Lowest level, typically 20 mW at 3.3 V: `0x1E` when long, `0x15` when short.
152 Low,
153}
154
155/// Duration selected for one bounded heater pulse.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum HeaterDuration {
158 /// Long operation: maximum 1.1 s, including the final high-repeatability measurement.
159 Long,
160 /// Short operation: maximum 0.11 s, including the final high-repeatability measurement.
161 Short,
162}
163
164/// One temperature and relative-humidity measurement.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub struct Measurement {
167 /// Temperature in thousandths of a degree Celsius.
168 pub t_mdeg_c: i32,
169 /// Relative humidity in thousandths of a percent.
170 pub rh_milli_pct: i32,
171}
172
173/// An SHT4x connected to abstract asynchronous I2C and delay resources.
174///
175/// # Cancellation safety
176///
177/// Command futures are not cancellation-safe after their I2C write may have
178/// been acknowledged. Dropping one can leave an operation in progress or a
179/// completed response unread, and this driver retains no in-flight state after
180/// the future is dropped. Do not issue another command through recovered
181/// resources until integration has re-established a known idle transaction
182/// state. Soft reset is documented to abort an action still in progress, but
183/// is not claimed to discard an already-completed unread response.
184pub struct Sht4x<I2C, DELAY> {
185 address: Address,
186 i2c: I2C,
187 delay: DELAY,
188}
189
190impl<I2C, DELAY> Sht4x<I2C, DELAY> {
191 /// Create a driver for one SHT4x at the given address.
192 ///
193 /// The address comes from position 7 of the part number, per
194 /// [`Address`]. Every operation on the returned driver addresses that one
195 /// device; nothing here scans the bus or infers which part is present.
196 pub const fn new(address: Address, i2c: I2C, delay: DELAY) -> Self {
197 Self {
198 address,
199 i2c,
200 delay,
201 }
202 }
203
204 /// The address this driver was constructed for.
205 #[must_use]
206 pub const fn address(&self) -> Address {
207 self.address
208 }
209
210 /// Read the device's 32-bit transmission-order serial number.
211 ///
212 /// Per `SHT4X-SN-CMD-001` this is a command write and then a *separate*
213 /// six-byte read — not a combined `write_read`. Between them the driver
214 /// applies the conservative 10 ms Sensirion-reference wait recorded by
215 /// `SHT4X-SN-WAIT-001`; that is an interoperability policy, not a
216 /// datasheet-stated device-busy maximum. Both response words are
217 /// CRC-validated under `SHT45-CRC-001`.
218 ///
219 /// For an SHT43 this serial is the key its ISO/IEC 17025 calibration
220 /// certificate is filed under (`SHT4X-SHT43-CAL-001`). Retrieving or
221 /// applying that certificate is outside this driver.
222 pub async fn read_serial_number<E>(&mut self) -> Result<u32, Error<E>>
223 where
224 I2C: I2c<Error = E>,
225 DELAY: DelayNs,
226 E: embedded_hal::i2c::Error,
227 {
228 self.i2c
229 .write(self.address.bits(), &[SERIAL_NUMBER_COMMAND])
230 .await
231 .map_err(map_i2c_error)?;
232
233 self.delay.delay_us(SERIAL_NUMBER_DURATION_US).await;
234
235 let mut response = [0; RESPONSE_LEN];
236 self.i2c
237 .read(self.address.bits(), &mut response)
238 .await
239 .map_err(map_i2c_error)?;
240
241 let (high, low) = decode_words(response)?;
242 Ok((u32::from(high) << 16) | u32::from(low))
243 }
244
245 /// Perform a soft reset and wait for the device to return to idle.
246 ///
247 /// Writes the command of `SHT45-RST-CMD-001`, which returns no payload, and
248 /// then waits the `SHT45-RST-TIME-001` idle-time bound. Per
249 /// `SHT45-RST-ABORT-001` this aborts an in-flight measurement or heater
250 /// pulse.
251 pub async fn reset<E>(&mut self) -> Result<(), Error<E>>
252 where
253 I2C: I2c<Error = E>,
254 DELAY: DelayNs,
255 E: embedded_hal::i2c::Error,
256 {
257 self.i2c
258 .write(self.address.bits(), &[SOFT_RESET_COMMAND])
259 .await
260 .map_err(map_i2c_error)?;
261
262 self.delay.delay_us(SOFT_RESET_DURATION_US).await;
263 Ok(())
264 }
265
266 /// Perform one temperature and relative-humidity measurement.
267 ///
268 /// Selects the command of `SHT45-MEAS-CMD-001` for the requested
269 /// repeatability and waits that repeatability's Table 5 **maximum** from
270 /// `SHT45-MEAS-TIME-001` rather than its typical value, then reads and
271 /// converts six bytes.
272 ///
273 /// Results are uncropped under `SHT45-MEAS-CONV-001`: a relative humidity
274 /// outside 0–100 %RH is returned as computed rather than clamped.
275 pub async fn measure<E>(
276 &mut self,
277 repeatability: Repeatability,
278 ) -> Result<Measurement, Error<E>>
279 where
280 I2C: I2c<Error = E>,
281 DELAY: DelayNs,
282 E: embedded_hal::i2c::Error,
283 {
284 let (command, duration_us) = match repeatability {
285 Repeatability::High => (0xfd, MEASUREMENT_HIGH_DURATION_US),
286 Repeatability::Medium => (0xf6, MEASUREMENT_MEDIUM_DURATION_US),
287 Repeatability::Low => (0xe0, MEASUREMENT_LOW_DURATION_US),
288 };
289
290 self.i2c
291 .write(self.address.bits(), &[command])
292 .await
293 .map_err(map_i2c_error)?;
294
295 self.delay.delay_us(duration_us).await;
296
297 let mut response = [0; RESPONSE_LEN];
298 self.i2c
299 .read(self.address.bits(), &mut response)
300 .await
301 .map_err(map_i2c_error)?;
302
303 decode_measurement(response)
304 }
305
306 /// Run one heater pulse and return its on-chip high-repeatability measurement.
307 ///
308 /// # The returned reading is not an ambient measurement
309 ///
310 /// Under `SHT45-HEAT-SEQ-001` the device converts *while the heater is still
311 /// on*, so the returned [`Measurement`] describes the heated sensor rather
312 /// than the surrounding air. How the two differ is heater physics, which this
313 /// repository does not retain, model, bound, or correct. It shares the
314 /// [`Measurement`] type with [`Sht4x::measure`] and is not a substitute for
315 /// it: use [`Sht4x::measure`] for a reading taken with the heater off. What
316 /// either reading implies about the surrounding air is a system-calibration
317 /// question this repository does not answer.
318 ///
319 /// The caller owns application-level heater policy, including the operating
320 /// limits recorded by `SHT4X-HEAT-USE-001`: total heater-on time over the
321 /// sensor's lifetime must remain below 10 percent; the heater must only be
322 /// operated below 65 °C ambient; sensor temperature must remain at or below
323 /// 125 °C; specifications are invalid while heating; and the supply must
324 /// tolerate up to approximately 75 mA at the highest setting. When driven
325 /// to completion, this operation owns the selected command's complete wait
326 /// and response read. A write that fails returns immediately, without
327 /// waiting or reading.
328 pub async fn heater_pulse<E>(
329 &mut self,
330 power: HeaterPower,
331 duration: HeaterDuration,
332 ) -> Result<Measurement, Error<E>>
333 where
334 I2C: I2c<Error = E>,
335 DELAY: DelayNs,
336 E: embedded_hal::i2c::Error,
337 {
338 let (command, duration_us) = match (duration, power) {
339 (HeaterDuration::Long, HeaterPower::High) => (0x39, HEATER_LONG_DURATION_US),
340 (HeaterDuration::Long, HeaterPower::Medium) => (0x2f, HEATER_LONG_DURATION_US),
341 (HeaterDuration::Long, HeaterPower::Low) => (0x1e, HEATER_LONG_DURATION_US),
342 (HeaterDuration::Short, HeaterPower::High) => (0x32, HEATER_SHORT_DURATION_US),
343 (HeaterDuration::Short, HeaterPower::Medium) => (0x24, HEATER_SHORT_DURATION_US),
344 (HeaterDuration::Short, HeaterPower::Low) => (0x15, HEATER_SHORT_DURATION_US),
345 };
346
347 self.i2c
348 .write(self.address.bits(), &[command])
349 .await
350 .map_err(map_i2c_error)?;
351
352 self.delay.delay_us(duration_us).await;
353
354 let mut response = [0; RESPONSE_LEN];
355 self.i2c
356 .read(self.address.bits(), &mut response)
357 .await
358 .map_err(map_i2c_error)?;
359
360 decode_measurement(response)
361 }
362
363 /// Return the underlying I2C bus and delay resources.
364 pub fn release(self) -> (I2C, DELAY) {
365 (self.i2c, self.delay)
366 }
367}
368
369fn map_i2c_error<E>(error: E) -> Error<E>
370where
371 E: embedded_hal::i2c::Error,
372{
373 match error.kind() {
374 embedded_hal::i2c::ErrorKind::NoAcknowledge(_) => Error::NoAcknowledge(error),
375 _ => Error::I2c(error),
376 }
377}
378
379#[inline(always)]
380fn crc8(bytes: [u8; 2]) -> u8 {
381 let mut crc = 0xff;
382
383 for byte in bytes {
384 crc ^= byte;
385
386 for _ in 0..8 {
387 let mask = 0u8.wrapping_sub(crc >> 7);
388 crc = (crc << 1) ^ (0x31 & mask);
389 }
390 }
391
392 crc
393}
394
395#[inline]
396fn div_65535(n: u32) -> u32 {
397 // Exact for the ranges used below.
398 (n + (n >> 16) + 1) >> 16
399}
400
401fn convert_temperature(ticks: u16) -> i32 {
402 let ticks = u32::from(ticks);
403
404 // 175_000 = 2 * 65_535 + 43_930
405 let fractional = div_65535(43_930 * ticks);
406
407 -45_000 + (2 * ticks + fractional) as i32
408}
409
410fn convert_humidity(ticks: u16) -> i32 {
411 let ticks = u32::from(ticks);
412
413 // 125_000 = 65_535 + 59_465
414 let fractional = div_65535(59_465 * ticks);
415
416 -6_000 + (ticks + fractional) as i32
417}
418
419/// Validate both CRC-8 bytes and return the two 16-bit words in transmission
420/// order.
421///
422/// Serial-number and measurement responses share this frame shape, so they
423/// share this decode. A CRC failure names the word it failed on.
424fn decode_words<E>(response: [u8; RESPONSE_LEN]) -> Result<(u16, u16), Error<E>> {
425 let first = u16::from_be_bytes([response[0], response[1]]);
426 let second = u16::from_be_bytes([response[3], response[4]]);
427 for (word, (value, actual)) in [(first, response[2]), (second, response[5])]
428 .into_iter()
429 .enumerate()
430 {
431 let expected = crc8(value.to_be_bytes());
432 if expected != actual {
433 return Err(Error::Crc {
434 word,
435 expected,
436 actual,
437 });
438 }
439 }
440
441 Ok((first, second))
442}
443
444fn decode_measurement<E>(response: [u8; RESPONSE_LEN]) -> Result<Measurement, Error<E>> {
445 let (temperature, humidity) = decode_words(response)?;
446 Ok(Measurement {
447 t_mdeg_c: convert_temperature(temperature),
448 rh_milli_pct: convert_humidity(humidity),
449 })
450}
451
452#[cfg(test)]
453mod tests;