Skip to main content

m5stack_core/driver/
ds18b20.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! DS18B20 1-Wire digital temperature sensor driver via RMT peripheral.
3//!
4//! Broadcasts a single Convert T to all sensors, waits for the conversion to
5//! complete, then uses the ROM Search algorithm to enumerate every sensor and
6//! reads each device's full 9-byte scratchpad (validating its CRC-8). The
7//! temperature (bytes 0..1) is returned as signed 12.4 fixed-point (0.0625 °C
8//! resolution).
9//!
10//! 1-Wire commands used:
11//!   0xCC  Skip ROM — address all devices
12//!   0x44  Convert T — start temperature conversion (750 ms max at 12-bit)
13//!   0x55  Match ROM — address specific device
14//!   0xBE  Read Scratchpad — returns 9 bytes (TEMP_LSB, TEMP_MSB, …, CRC)
15//!
16//! RMT channel assignment (chip-specific):
17//!   ESP32 (fire27):   TX=channel0, RX=channel2
18//!   ESP32-S3 (cores3): TX=channel0, RX=channel4
19//!
20//! Wiring (M5Stack Grove): the 1-Wire data line goes on **Port B (black)** — the
21//! signal pin that follows VCC, i.e. **G26** on Fire27 and **G9** on CoreS3. An
22//! external 4.7 kΩ pull-up from data to 3V3 is required. (Port A / red is the
23//! I2C port and is not used here.)
24//!
25//! Datasheet: <https://www.analog.com/media/en/technical-documentation/data-sheets/DS18B20.pdf>
26use crate::driver::onewire::{Address, OneWire, Search, SearchError, crc8};
27use embassy_time::{Duration, Instant, Timer};
28use esp_hal::{
29    Async,
30    gpio::AnyPin,
31    peripherals::RMT,
32    rmt::{Rmt, RxChannelCreator, TxChannelCreator},
33    time::Rate,
34};
35use heapless::Vec;
36use thiserror_no_std::Error;
37
38#[derive(Debug, Error)]
39pub enum Error {
40    #[error("failed to configure the RMT peripheral: {0:?}")]
41    RmtConfigError(#[from] esp_hal::rmt::ConfigError),
42    #[error("temperature conversion did not complete within 750 ms")]
43    ConversionTimeout,
44    #[error("DS18B20 scratchpad failed its CRC-8 check")]
45    ScratchpadCrcMismatch,
46    #[error("DS18B20 scratchpad read back all 0x00 or all 0xFF -- nobody answered")]
47    ScratchpadNotAnswered,
48    #[error("1-Wire bus error: {0}")]
49    OneWireError(#[from] crate::driver::onewire::Error),
50    #[error("more sensors connected than the driver supports")]
51    TooManySensorsConnected,
52}
53
54pub struct Ds18b20Driver {
55    ow: OneWire<'static>,
56    /// Whether ANY device on the bus is parasite-powered, as the bus itself
57    /// reports it (`0xB4`). Re-established by [`Self::rescan`].
58    parasitic: bool,
59    /// ROM addresses discovered by the last scan, reused across reads.
60    addresses: Vec<Address, { Self::MAX_SENSORS }>,
61}
62
63impl Ds18b20Driver {
64    const MAX_SENSORS: usize = 16;
65    /// Claim the WHOLE RMT peripheral and drive `pin` as the 1-Wire bus.
66    ///
67    /// Convenience for an app that uses RMT for nothing else. If it also drives
68    /// the SK6812 bars, use [`Self::with_channels`] and
69    /// [`crate::driver::sk6812::Sk6812Driver::with_channel`] with channels from
70    /// [`crate::board::rmt::RmtChannels`] — both drivers used to take the
71    /// peripheral by value and both wanted channel 0, so having temperature
72    /// sensing meant having no LEDs.
73    pub fn new(rmt: RMT<'static>, pin: AnyPin<'static>) -> Result<Self, Error> {
74        let rmt = Rmt::new(rmt, Rate::from_mhz(80_u32))?.into_async();
75        // ESP32: TX channel 0, RX channel 2
76        // ESP32-S3: TX channels 0-3, RX channels 4-7
77        #[cfg(feature = "fire27")]
78        let r = Self::with_channels(rmt.channel0, rmt.channel2, pin);
79        #[cfg(feature = "cores3")]
80        let r = Self::with_channels(rmt.channel0, rmt.channel4, pin);
81        r
82    }
83
84    /// Drive `pin` as the 1-Wire bus using the given RMT channels.
85    ///
86    /// One TX and one RX channel, which leaves the rest of the peripheral for
87    /// other users — the point of the split. The bit timing is the RMT's, so
88    /// which channel it is does not matter to this driver.
89    pub fn with_channels(
90        tx: impl TxChannelCreator<'static, Async>,
91        rx: impl RxChannelCreator<'static, Async>,
92        pin: AnyPin<'static>,
93    ) -> Result<Self, Error> {
94        Ok(Ds18b20Driver {
95            ow: OneWire::new(tx, rx, pin)?,
96            addresses: Vec::new(),
97            parasitic: false,
98        })
99    }
100
101    /// Enumerate the bus and cache the discovered ROM addresses.
102    ///
103    /// Runs the full ROM Search once. [`read_all_temperatures`] calls this
104    /// lazily on first use; call it explicitly to refresh the set. As no sensor
105    /// hot-plug is assumed at runtime, the cached addresses are reused across
106    /// reads — avoiding a 64-step ROM search on every cycle (which otherwise
107    /// dominates the RMT round-trips and task wakeups, the main cost here since
108    /// the RMT does the bit timing in hardware).
109    /// Drop the cached ROM addresses, so the next read enumerates again.
110    ///
111    /// For a caller recovering from a bus error: the cache (and the power mode
112    /// that came with it) describes a bus that was working, and after a fault
113    /// neither can be assumed.
114    pub fn forget_addresses(&mut self) {
115        self.addresses.clear();
116    }
117
118    pub async fn rescan(&mut self) -> Result<(), Error> {
119        self.addresses.clear();
120        let mut search = Search::new();
121        loop {
122            match search.next(&mut self.ow).await {
123                Ok(address) => {
124                    debug!("found device {}", address);
125                    if self.addresses.push(address).is_err() {
126                        return Err(Error::TooManySensorsConnected);
127                    }
128                }
129                // A corrupt ROM CRC affects only this one enumeration step; the
130                // search state has advanced, so keep scanning the rest.
131                Err(SearchError::CrcMismatch) => warn!("ROM CRC mismatch, skipping device"),
132                Err(SearchError::SearchComplete) | Err(SearchError::NoDevicesPresent) => break,
133                Err(SearchError::BusError(e)) => return Err(e.into()),
134            }
135        }
136        self.parasitic = self.bus_is_parasitic().await?;
137        if self.parasitic {
138            info!("1-Wire: parasite-powered device present, conversions will hold the bus high");
139        }
140        Ok(())
141    }
142
143    /// Ask the bus how it is powered: Read Power Supply (`0xB4`) after a Skip
144    /// ROM, where **any** parasite-powered device pulls the following read slot
145    /// low. The answer is deliberately bus-wide and conservative: a strong
146    /// pull-up does no harm to an externally-powered device, so a mixed bus is
147    /// treated as parasitic.
148    async fn bus_is_parasitic(&mut self) -> Result<bool, Error> {
149        if self.addresses.is_empty() {
150            return Ok(false);
151        }
152        self.ow.reset().await?;
153        for cmd in [0xCC, 0xB4] {
154            self.ow.send_byte(cmd).await?;
155        }
156        let mut bit = [false; 1];
157        self.ow.exchange_bits(&[true], &mut bit).await?;
158        Ok(!bit[0])
159    }
160
161    pub async fn read_all_temperatures(
162        &mut self,
163    ) -> Result<impl Iterator<Item = (Address, f32)>, Error> {
164        if self.addresses.is_empty() {
165            self.rescan().await?;
166        }
167
168        // Presence FIRST, and acted on: a reset with nobody answering means
169        // the bus is empty, whatever is cached. Forgetting the addresses makes
170        // the caller see an empty result -- so a pulled sensor reads as absent
171        // rather than keeping its last value -- and makes the next cycle
172        // enumerate, so plugging it back in brings it back by itself.
173        if !self.ow.reset().await? {
174            if !self.addresses.is_empty() {
175                warn!(
176                    "1-Wire: no presence pulse, dropping {} cached sensor(s)",
177                    self.addresses.len()
178                );
179                self.addresses.clear();
180            }
181            return Ok(Vec::new().into_iter());
182        }
183
184        // Re-read how the bus is powered on every cycle, not just at a scan:
185        // a sensor rewired from three wires to two (or back) would otherwise
186        // keep the stale mode, and one direction is silently wrong -- polling
187        // a parasite device returns at once and yields a stale reading with a
188        // VALID CRC.
189        self.parasitic = self.bus_is_parasitic().await?;
190
191        trace!("Broadcasting a measure temperature command to all attached sensors");
192        self.ow.reset().await?;
193        for cmd in [0xCC, 0x44] {
194            self.ow.send_byte(cmd).await?;
195        }
196
197        // A read immediately after Convert T returns the *previous* conversion
198        // (the very first read after power-up is the 85 °C reset value). Wait
199        // for completion before reading so callers get the fresh measurement.
200        self.wait_conversion_complete().await?;
201
202        // Read each cached sensor by ROM address. A sensor that drops out is
203        // warned and omitted from this cycle's results; since no hot-plug is
204        // assumed, its address stays cached so it is retried on the next read.
205        let mut temperatures = Vec::<(Address, f32), { Self::MAX_SENSORS }>::new();
206        for i in 0..self.addresses.len() {
207            let address = self.addresses[i];
208            match self.read_scratchpad(address).await {
209                Ok(temperature_celsius) => {
210                    // Capacity is guaranteed: addresses.len() <= MAX_SENSORS.
211                    let _ = temperatures.push((address, temperature_celsius));
212                    debug!("sensor {}: {}°C", address, temperature_celsius);
213                }
214                Err(e) => warn!("sensor {} lost: {:?}", address, e),
215            }
216        }
217        // Fewer answers than cached means the bus changed under us. Drop the
218        // cache so the next cycle enumerates: that is what lets a sensor
219        // re-appear after it is plugged back in, and it keeps the cached set
220        // from describing a bus that no longer exists.
221        if temperatures.len() < self.addresses.len() {
222            warn!(
223                "1-Wire: {} of {} sensors answered, re-enumerating next cycle",
224                temperatures.len(),
225                self.addresses.len()
226            );
227            self.addresses.clear();
228        }
229        Ok(temperatures.into_iter())
230    }
231
232    /// Worst-case conversion time: 12-bit resolution, the reset default.
233    const CONVERSION_TIME: Duration = Duration::from_millis(750);
234
235    /// Wait for the in-progress conversion, however the bus is powered.
236    ///
237    /// Externally powered: poll. The device holds the bus low while converting
238    /// and releases it (a read slot returns 1) when done, so this finishes as
239    /// soon as the slowest sensor does and reports
240    /// [`Error::ConversionTimeout`] if none ever does.
241    ///
242    /// Parasite-powered: do not poll — the device cannot answer a read slot
243    /// while converting and the datasheet forbids asking. Feed it instead
244    /// ([`OneWire::strong_pull_up`]) for the full conversion time. The cost is
245    /// that a dead sensor can no longer be detected here; it surfaces one step
246    /// later as a scratchpad read with a bad CRC, which makes that check
247    /// load-bearing on a parasitic bus.
248    async fn wait_conversion_complete(&mut self) -> Result<(), Error> {
249        if self.parasitic {
250            self.ow.strong_pull_up(Self::CONVERSION_TIME).await?;
251            return Ok(());
252        }
253        let start = Instant::now();
254        loop {
255            let mut bit = [false; 1];
256            self.ow.exchange_bits(&[true], &mut bit).await?;
257            if bit[0] {
258                return Ok(());
259            }
260            if start.elapsed() > Duration::from_millis(800) {
261                return Err(Error::ConversionTimeout);
262            }
263            // Conversion is signalled by the read-slot result above, not by this
264            // delay; it only paces the poll so we don't hammer the bus.
265            Timer::after(Duration::from_millis(10)).await;
266        }
267    }
268
269    /// Address a single device, read its full 9-byte scratchpad, validate the
270    /// CRC, and return the temperature in °C.
271    async fn read_scratchpad(&mut self, address: Address) -> Result<f32, Error> {
272        self.ow.reset().await?;
273        self.ow.send_byte(0x55).await?; // Match ROM
274        self.ow.send_address(address).await?;
275        self.ow.send_byte(0xBE).await?; // Read Scratchpad
276        let mut scratch = [0u8; 9];
277        for byte in scratch.iter_mut() {
278            // Propagates as `OneWireError`, preserving the underlying bus error.
279            *byte = self.ow.exchange_byte(0xFF).await?;
280        }
281        // An all-zero scratchpad PASSES the CRC -- crc8 of eight 0x00 bytes is
282        // 0x00 -- and decodes as a perfectly plausible 0 degC. A bus held low
283        // therefore reads as data rather than as a fault, which is worse than
284        // an error. All-0xFF (a released bus) fails the CRC anyway, but reject
285        // it here too so the error says what happened.
286        if scratch.iter().all(|&b| b == 0x00) || scratch.iter().all(|&b| b == 0xFF) {
287            return Err(Error::ScratchpadNotAnswered);
288        }
289        // Byte 8 is a CRC-8 over bytes 0..8; reject a corrupt read.
290        if crc8(&scratch[..8]) != scratch[8] {
291            return Err(Error::ScratchpadCrcMismatch);
292        }
293        Ok(fixed::types::I12F4::from_le_bytes([scratch[0], scratch[1]]).into())
294    }
295}