embedded-devices 0.10.3

Device driver implementations for many embedded sensors and devices
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
//! The MAX31865 is an easy-to-use resistance-to-digital converter optimized for platinum
//! resistance temperature detectors (RTDs). An external resistor sets the sensitivity
//! for the RTD being used and a precision delta-sigma ADC converts the ratio of the RTD
//! resistance to the reference resistance into digital form. The MAX31865's inputs are
//! protected against overvoltage faults as large as ±45V. Programmable detection of RTD
//! and cable open and short conditions is included.
//!
//! ## Usage (sync)
//!
//! ```rust
//! # #[cfg(feature = "sync")] mod test {
//! # fn test<I, D>(mut spi: I, delay: D) -> Result<(), embedded_devices::devices::analog_devices::max31865::MeasurementError<I::Error>>
//! # where
//! #   I: embedded_hal::spi::SpiDevice,
//! #   D: embedded_hal::delay::DelayNs
//! # {
//! use embedded_devices::devices::analog_devices::max31865::{MAX31865Sync, registers::{FilterMode, Resistance, WiringMode}};
//! use embedded_devices::sensor::OneshotSensorSync;
//! use uom::si::thermodynamic_temperature::degree_celsius;
//!
//! // Create and initialize the device
//! let mut max31865 = MAX31865Sync::new_spi(delay, spi, 4.3);
//! max31865.init(WiringMode::ThreeWire, FilterMode::F_50Hz).unwrap();
//!
//! let temp = max31865.measure()?
//!     .temperature.get::<degree_celsius>();
//! println!("Current temperature: {:?}°C", temp);
//! # Ok(())
//! # }
//! # }
//! ```
//!
//! ## Usage (async)
//!
//! ```rust
//! # #[cfg(feature = "async")] mod test {
//! # async fn test<I, D>(mut spi: I, delay: D) -> Result<(), embedded_devices::devices::analog_devices::max31865::MeasurementError<I::Error>>
//! # where
//! #   I: embedded_hal_async::spi::SpiDevice,
//! #   D: embedded_hal_async::delay::DelayNs
//! # {
//! use embedded_devices::devices::analog_devices::max31865::{MAX31865Async, registers::{FilterMode, Resistance, WiringMode}};
//! use embedded_devices::sensor::OneshotSensorAsync;
//! use uom::si::thermodynamic_temperature::degree_celsius;
//!
//! // Create and initialize the device
//! let mut max31865 = MAX31865Async::new_spi(delay, spi, 4.3);
//! max31865.init(WiringMode::ThreeWire, FilterMode::F_50Hz).await.unwrap();
//!
//! let temp = max31865.measure().await?
//!     .temperature.get::<degree_celsius>();
//! println!("Current temperature: {:?}°C", temp);
//! # Ok(())
//! # }
//! # }
//! ```

use embedded_devices_derive::forward_register_fns;
use embedded_devices_derive::sensor;
use embedded_interfaces::TransportError;
use registers::{
    Configuration, ConversionMode, FaultDetectionCycle, FaultThresholdHigh, FaultThresholdLow, FilterMode, WiringMode,
};
use uom::si::f64::ThermodynamicTemperature;
use uom::si::thermodynamic_temperature::degree_celsius;

use crate::utils::callendar_van_dusen;

pub mod registers;

#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, thiserror::Error)]
pub enum FaultDetectionError<BusError> {
    /// Transport error
    #[error("transport error")]
    Transport(#[from] TransportError<(), BusError>),
    /// Timeout (the detection never finished in the allocated time frame)
    #[error("fault detection timeout")]
    Timeout,
    /// A fault was detected. Read the FaultStatus register for details.
    #[error("fault detected")]
    FaultDetected,
}

#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, thiserror::Error)]
pub enum MeasurementError<BusError> {
    /// Transport error
    #[error("transport error")]
    Transport(#[from] TransportError<(), BusError>),
    /// A fault was detected. Read the FaultStatus register for details.
    #[error("fault detected")]
    FaultDetected,
}

/// Measurement data
#[derive(Debug, embedded_devices_derive::Measurement)]
pub struct Measurement {
    /// Current temperature
    #[measurement(Temperature)]
    pub temperature: ThermodynamicTemperature,
}

/// The MAX31865 is an easy-to-use resistance-to-digital converter optimized for platinum
/// resistance temperature detectors (RTDs).
///
/// For a full description and usage examples, refer to the [module documentation](self).
#[maybe_async_cfg::maybe(
    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), RegisterInterface),
    sync(feature = "sync"),
    async(feature = "async")
)]
pub struct MAX31865<D: hal::delay::DelayNs, I: embedded_interfaces::registers::RegisterInterface> {
    /// The delay provider
    delay: D,
    /// The interface to communicate with the device
    interface: I,
    /// The reference resistor value over to the nominal resistance of
    /// the temperature element at 0°C (100Ω for PT100, 1000Ω for PT1000).
    /// In many designs a resistor with a value of 4.3 times the nominal resistance is used,
    /// but your design may vary.
    reference_resistor_ratio: f64,
}

pub trait MAX31865Register {}

#[maybe_async_cfg::maybe(
    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), SpiDevice),
    sync(feature = "sync"),
    async(feature = "async")
)]
impl<D, I> MAX31865<D, embedded_interfaces::spi::SpiDevice<I>>
where
    I: hal::spi::r#SpiDevice,
    D: hal::delay::DelayNs,
{
    /// Initializes a new device from the specified SPI device.
    /// This consumes the SPI device `I`.
    ///
    /// The device supports SPI modes 1 and 3.
    ///
    /// The reference resistor ratio is defined as the reference resistor value over the nominal resistance of
    /// the temperature element at 0°C (100Ω for PT100, 1000Ω for PT1000).
    /// In many designs a resistor with a value of 4.3 times the nominal resistance is used,
    /// but your design may vary.
    #[inline]
    pub fn new_spi(delay: D, interface: I, reference_resistor_ratio: f64) -> Self {
        Self {
            delay,
            interface: embedded_interfaces::spi::SpiDevice::new(interface),
            reference_resistor_ratio,
        }
    }
}

#[forward_register_fns]
#[sensor(Temperature)]
#[maybe_async_cfg::maybe(
    idents(hal(sync = "embedded_hal", async = "embedded_hal_async"), RegisterInterface),
    sync(feature = "sync"),
    async(feature = "async")
)]
impl<D: hal::delay::DelayNs, I: embedded_interfaces::registers::RegisterInterface> MAX31865<D, I> {
    /// Initializes the device by configuring important settings and
    /// running an initial fault detection cycle.
    // TODO call this configure, make init verify device communication and reset
    pub async fn init(
        &mut self,
        wiring_mode: WiringMode,
        filter_mode: FilterMode,
    ) -> Result<(), FaultDetectionError<I::BusError>> {
        // Configure the wiring mode and filter mode
        self.write_register(
            Configuration::default()
                .with_wiring_mode(wiring_mode)
                .with_filter_mode(filter_mode),
        )
        .await?;

        self.write_register(FaultThresholdLow::default().with_resistance_ratio(0))
            .await?;
        self.write_register(FaultThresholdHigh::default().with_resistance_ratio(0x7fff))
            .await?;

        self.detect_faults().await
    }

    /// Runs the automatic fault detection.
    pub async fn detect_faults(&mut self) -> Result<(), FaultDetectionError<I::BusError>> {
        let reg_conf = self.read_register::<Configuration>().await?;

        // The automatic fault detection waits 100µs before checking for faults,
        // which should be plenty of time to charge the RC filter.
        // Typically a 100nF cap is used which should charge significantly faster.
        self.write_register(
            reg_conf
                .with_enable_bias_voltage(true)
                .with_conversion_mode(ConversionMode::NormallyOff)
                .with_clear_fault_status(false)
                .with_fault_detection_cycle(FaultDetectionCycle::Automatic),
        )
        .await?;

        // According to the flow diagram in the datasheet, automatic calibration waits
        // a total of 510µs. We will wait for a bit longer initially and then check
        // the status in the configuration register up to 5 times with some additional delay.
        self.delay.delay_us(550).await;
        const TRIES: u8 = 5;
        for _ in 0..TRIES {
            let cycle = self
                .read_register::<Configuration>()
                .await?
                .read_fault_detection_cycle();

            // Check if fault detection is done
            if cycle == FaultDetectionCycle::Finished {
                // Disable VBIAS
                self.write_register(reg_conf.with_enable_bias_voltage(false)).await?;

                let has_fault = self.read_register::<registers::Resistance>().await?.read_fault();
                if has_fault {
                    // Fault detected
                    return Err(FaultDetectionError::FaultDetected);
                } else {
                    // Everything's fine!
                    return Ok(());
                }
            }

            self.delay.delay_us(100).await;
        }

        // Disable VBIAS
        self.write_register(reg_conf.with_enable_bias_voltage(false)).await?;

        Err(FaultDetectionError::Timeout)
    }

    /// Converts a temperature into a resistance ratio as understood
    /// by the device by factoring in the reference resistor ratio
    /// and converting it to the required raw data format for this device.
    ///
    /// If the temperature results in a ratio >= 1.0, the resulting value will be clamped
    /// to the maximum representable ratio (1.0).
    pub fn temperature_to_raw_resistance_ratio(&mut self, temperature: ThermodynamicTemperature) -> u16 {
        let temperature = temperature.get::<degree_celsius>() as f32;
        let resistance = callendar_van_dusen::temperature_to_resistance_r100(temperature);
        let ratio = resistance / (100.0 * self.reference_resistor_ratio) as f32;
        if ratio >= 1.0 {
            (1 << 15) - 1
        } else {
            (ratio * (1 << 15) as f32) as u16
        }
    }

    /// Converts a raw resistance ratio into a temperature by
    /// utilizing a builtin inverse Callendar-Van Dusen lookup table.
    pub fn raw_resistance_ratio_to_temperature(&mut self, raw_resistance: u16) -> ThermodynamicTemperature {
        // We always calculate with a 100Ω lookup table, because the equation
        // linearly scales to other temperature ranges. Only the ratio between
        // reference resistor and PT element is important.
        let resistance = (100.0 * raw_resistance as f32 * self.reference_resistor_ratio as f32) / ((1 << 15) as f32);
        let temperature = callendar_van_dusen::resistance_to_temperature_r100(resistance);
        ThermodynamicTemperature::new::<degree_celsius>(temperature as f64)
    }

    /// Read the latest resistance measurement from the device register and convert
    /// it to a temperature by using the internal Callendar-Van Dusen lookup table.
    ///
    /// Checks for faults.
    pub async fn read_temperature(&mut self) -> Result<ThermodynamicTemperature, MeasurementError<I::BusError>> {
        let resistance = self.read_register::<registers::Resistance>().await?;

        if resistance.read_fault() {
            return Err(MeasurementError::FaultDetected);
        }

        Ok(self.raw_resistance_ratio_to_temperature(resistance.read_resistance_ratio()))
    }
}

#[maybe_async_cfg::maybe(
    idents(
        hal(sync = "embedded_hal", async = "embedded_hal_async"),
        RegisterInterface,
        OneshotSensor
    ),
    sync(feature = "sync"),
    async(feature = "async")
)]
impl<D: hal::delay::DelayNs, I: embedded_interfaces::registers::RegisterInterface> crate::sensor::OneshotSensor
    for MAX31865<D, I>
{
    type Error = MeasurementError<I::BusError>;
    type Measurement = Measurement;

    /// Performs a one-shot measurement. This will enable bias voltage, transition the device into
    /// oneshot mode, which will cause it to take a measurement and return to sleep mode
    /// afterwards.
    async fn measure(&mut self) -> Result<Self::Measurement, Self::Error> {
        let reg_conf = self
            .read_register::<Configuration>()
            .await?
            .with_enable_bias_voltage(false)
            .with_conversion_mode(ConversionMode::NormallyOff)
            .with_oneshot(false);

        // Enable VBIAS before initiating one-shot measurement,
        // 10.5 RC time constants are recommended plus 1ms extra.
        // So we just wait 2ms which should be plenty of time.
        self.write_register(reg_conf.with_enable_bias_voltage(true)).await?;
        self.delay.delay_us(2000).await;

        // Initiate measurement
        self.write_register(reg_conf.with_enable_bias_voltage(true).with_oneshot(true))
            .await?;

        // Wait until measurement is ready, plus 2ms extra
        let measurement_time_us = match reg_conf.read_filter_mode() {
            FilterMode::F_60Hz => 52000,
            FilterMode::F_50Hz => 62500,
        };
        self.delay.delay_us(2000 + measurement_time_us).await;

        // Revert config (disable VBIAS)
        self.write_register(reg_conf).await?;

        // Return conversion result
        Ok(Measurement {
            temperature: self.read_temperature().await?,
        })
    }
}

#[maybe_async_cfg::maybe(
    idents(
        hal(sync = "embedded_hal", async = "embedded_hal_async"),
        RegisterInterface,
        ContinuousSensor
    ),
    sync(feature = "sync"),
    async(feature = "async")
)]
impl<D: hal::delay::DelayNs, I: embedded_interfaces::registers::RegisterInterface> crate::sensor::ContinuousSensor
    for MAX31865<D, I>
{
    type Error = MeasurementError<I::BusError>;
    type Measurement = Measurement;

    /// Starts continuous measurement.
    async fn start_measuring(&mut self) -> Result<(), Self::Error> {
        let reg_conf = self.read_register::<Configuration>().await?;

        // Enable VBIAS and automatic conversions
        self.write_register(
            reg_conf
                .with_enable_bias_voltage(true)
                .with_conversion_mode(ConversionMode::Automatic)
                .with_oneshot(false),
        )
        .await?;

        Ok(())
    }

    /// Stops continuous measurement.
    async fn stop_measuring(&mut self) -> Result<(), Self::Error> {
        let reg_conf = self.read_register::<Configuration>().await?;

        // Disable VBIAS and automatic conversions, back to sleep.
        self.write_register(
            reg_conf
                .with_enable_bias_voltage(false)
                .with_conversion_mode(ConversionMode::NormallyOff)
                .with_oneshot(false),
        )
        .await?;

        Ok(())
    }

    /// Expected amount of time between measurements in microseconds.
    async fn measurement_interval_us(&mut self) -> Result<u32, Self::Error> {
        let reg_conf = self.read_register::<Configuration>().await?;
        let measurement_time_us = match reg_conf.read_filter_mode() {
            FilterMode::F_60Hz => 1_000_000 / 60,
            FilterMode::F_50Hz => 1_000_000 / 50,
        };

        Ok(measurement_time_us)
    }

    /// Returns the most recent measurement. Will never return None.
    async fn current_measurement(&mut self) -> Result<Option<Self::Measurement>, Self::Error> {
        Ok(Some(Measurement {
            temperature: self.read_temperature().await?,
        }))
    }

    /// Not supported through registers
    async fn is_measurement_ready(&mut self) -> Result<bool, Self::Error> {
        // TODO: could be supported by supplying ¬DRDY pin optionally in new
        Ok(true)
    }

    /// Opportunistically waits one conversion interval and returns the measurement.
    async fn next_measurement(&mut self) -> Result<Self::Measurement, Self::Error> {
        let interval = self.measurement_interval_us().await?;
        self.delay.delay_us(interval).await;
        self.current_measurement().await?.ok_or_else(|| {
            MeasurementError::Transport(TransportError::Unexpected(
                "measurement was not ready even though we expected it to be",
            ))
        })
    }
}