m5stack_core/driver/onewire.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! 1-Wire master over the ESP32 RMT peripheral (async).
3//!
4//! Vendored from the `esp-hal-rmt-onewire` crate (v0.4.0) by **jonored**
5//! — <https://github.com/jonored/esp-hal-rmt-onewire> — dual-licensed
6//! MIT OR Apache-2.0 (its `LICENSE-MIT` reads "Copyright 2021 esp-rs").
7//! Original authorship and copyright are retained, with thanks to the author.
8//!
9//! Adapted for in-tree use: updated for the esp-hal 1.x RMT API, and the
10//! const-generic `exchange_bits` reworked to a slice form (dropping the
11//! `generic_const_exprs` nightly feature) — modified from the original.
12
13use core::fmt::LowerHex;
14use embassy_futures::join::join;
15use embassy_futures::select::*;
16use embassy_time::{Duration, Timer};
17use esp_hal::rmt::{Rx, Tx};
18use esp_hal::{
19 Async,
20 gpio::{
21 DriveMode, DriveStrength, Flex, InputConfig, Level, OutputConfig, Pin, Pull,
22 interconnect::*,
23 },
24 rmt::{
25 Channel, ConfigError, PulseCode, RxChannelConfig, RxChannelCreator, TxChannelConfig,
26 TxChannelCreator,
27 },
28};
29use thiserror_no_std::Error as ThisError;
30
31// --- RMT timing -------------------------------------------------------------
32// The RMT is clocked at 80 MHz (see `Rmt::new` in the DS18B20 driver) and every
33// channel here uses a clock divider of 80, giving exactly one tick per
34// microsecond. Consequently all pulse lengths in this module are in µs.
35/// RMT clock divider: 80 MHz / 80 = 1 MHz ⇒ 1 µs per tick.
36const RMT_CLK_DIVIDER: u8 = 80;
37/// RX end-of-frame: capture stops once the bus stays idle this long (µs). Well
38/// above a single slot (~73 µs) but below the 480 µs reset, so the idle tail of
39/// each transaction terminates the capture.
40const RX_IDLE_THRESHOLD: u16 = 1000;
41/// RX glitch filter (source-clock cycles): shorter pulses are rejected as edge
42/// noise on slot transitions.
43const RX_FILTER_THRESHOLD: u8 = 10;
44
45/// Async 1-Wire bus master built on a pair of RMT TX/RX channels.
46pub struct OneWire<'a> {
47 rx: Channel<'a, Async, Rx>,
48 tx: Channel<'a, Async, Tx>,
49 input: InputSignal<'a>,
50}
51
52impl<'a> OneWire<'a> {
53 /// The TX channel's resting configuration. One definition, because
54 /// [`Self::strong_pull_up`] has to restore it.
55 fn tx_config() -> TxChannelConfig {
56 TxChannelConfig::default()
57 .with_clk_divider(RMT_CLK_DIVIDER)
58 .with_carrier_modulation(false)
59 }
60
61 /// Create a 1-Wire master driving `pin` (open-drain, pull-up) using the
62 /// supplied RMT TX and RX channel creators.
63 pub fn new<Txc: TxChannelCreator<'a, Async>, Rxc: RxChannelCreator<'a, Async>, P: Pin + 'a>(
64 txcc: Txc,
65 rxcc: Rxc,
66 pin: P,
67 ) -> Result<Self, Error> {
68 let rx_config = RxChannelConfig::default()
69 .with_clk_divider(RMT_CLK_DIVIDER)
70 .with_idle_threshold(RX_IDLE_THRESHOLD)
71 .with_filter_threshold(RX_FILTER_THRESHOLD)
72 .with_carrier_modulation(false);
73 let tx_config = Self::tx_config();
74
75 // Open-drain with an internal pull-up: a 1-Wire master only ever drives
76 // the bus low or releases it. An external 4.7 kΩ pull-up is still
77 // required for reliable edges with multiple devices / long cabling.
78 let mut pin: Flex = Flex::new(pin);
79
80 pin.apply_input_config(&InputConfig::default().with_pull(Pull::Up));
81 pin.apply_output_config(
82 &OutputConfig::default()
83 .with_drive_mode(DriveMode::OpenDrain)
84 .with_drive_strength(DriveStrength::_40mA),
85 );
86 pin.set_input_enable(true);
87 pin.set_output_enable(true);
88 let (input, output) = pin.split();
89
90 // The RMT idles its output high, which on an open-drain pad would *drive*
91 // the bus. Invert TX so an RMT `High` symbol pulls the bus LOW (an active
92 // 1-Wire drive) and a `Low` symbol releases it to the pull-up; invert RX
93 // to match, so a captured `length1` measures the bus-low duration.
94 let tx = txcc
95 .configure_tx(&tx_config)?
96 .with_pin(output.with_output_inverter(true));
97 let rx = rxcc
98 .configure_rx(&rx_config)?
99 .with_pin(input.clone().with_input_inverter(true));
100
101 // NOTE: `with_pin` applies `OutputConfig::default()` -- push-pull,
102 // 20 mA, no pull -- AFTER the config above, and `Flex::split` does not
103 // freeze the signals, so the open-drain pad set up here does not
104 // survive. Left alone deliberately: this is the configuration the bus
105 // has always run on and it works. "Fixing" it needs a handle to a pad
106 // the channels now own, and taking one anyway (`AnyPin::steal`) wedged
107 // the APP-core executor -- three owners of one pad, and the stolen
108 // handle's `Drop` restores the pin out from under the RMT.
109 Ok(OneWire { rx, tx, input })
110 }
111}
112
113impl<'a> OneWire<'a> {
114 /// Hold the bus HIGH for `duration`, then release it.
115 ///
116 /// This is the parasite-power path. A device whose Vdd is tied to GND draws
117 /// its conversion current -- up to 1.5 mA -- from the data line, and a
118 /// 4.7 kOhm pull-up cannot supply that: it sources 0.7 mA at 3.3 V, so the
119 /// line sags and the device's internal cap cannot carry the conversion. The
120 /// pad sources tens of mA instead, so no external strong pull-up is needed.
121 ///
122 /// Mechanically: the RMT is told to drive its idle output (which the TX
123 /// inverter turns into a HIGH pad), and the pad is switched to push-pull so
124 /// that "high" is driven rather than released. Both are undone afterwards.
125 ///
126 /// The bus MUST NOT be touched while this runs: a parasite device cannot
127 /// answer a read slot during its conversion, and the datasheet forbids
128 /// trying.
129 pub async fn strong_pull_up(&mut self, duration: Duration) -> Result<(), Error> {
130 // The pad is push-pull (see `new`), so the RMT driving its idle output
131 // low -- which the TX inverter turns into a HIGH pad -- is the strong
132 // pull-up. No pad handle, no second owner, no `unsafe`: the channel
133 // reconfigures itself and hands the bus back the same way.
134 let idle_high = Self::tx_config()
135 .with_idle_output(true)
136 .with_idle_output_level(Level::Low);
137 self.tx.apply_config(&idle_high)?;
138
139 Timer::after(duration).await;
140
141 self.tx.apply_config(&Self::tx_config())?;
142 Ok(())
143 }
144
145 /// Issue a 1-Wire reset pulse and return `true` if at least one device
146 /// responded with a presence pulse.
147 pub async fn reset(&mut self) -> Result<bool, Error> {
148 // Reset/presence sequence (DS18B20 datasheet "RESET PROCEDURE"). Recall
149 // the TX inverter: an RMT `Low` symbol releases the bus (pull-up high), a
150 // `High` symbol drives it low. So this is: 60 µs released lead-in, 600 µs
151 // reset low (≥480 µs required), then 600 µs released during which any
152 // present device asserts its presence pulse.
153 let data = [
154 PulseCode::new(Level::Low, 60, Level::High, 600),
155 PulseCode::new(Level::Low, 600, Level::Low, 0),
156 PulseCode::end_marker(),
157 ];
158 let mut indata = [PulseCode::end_marker(); 10];
159
160 let _res = self.send_and_receive(&mut indata, &data).await?;
161
162 // A present device pulls the bus low for 60–240 µs after the reset is
163 // released. Require both edges of the first captured symbol plus a
164 // second-symbol low inside a 100–200 µs window (within the presence
165 // spec, margined against noise).
166 Ok(indata[0].length1() > 0
167 && indata[0].length2() > 0
168 && indata[1].length1() > 100
169 && indata[1].length1() < 200)
170 }
171
172 /// Upper bound on a single bus transaction before the RX channel is treated
173 /// as stuck. Every DS18B20 reset/slot completes well under this; the long
174 /// temperature-conversion wait is handled by the caller, not here.
175 const RX_TIMEOUT: Duration = Duration::from_millis(10);
176
177 /// Transmit `data` while simultaneously sampling the bus into `indata`,
178 /// returning the number of received RMT symbols.
179 pub async fn send_and_receive(
180 &mut self,
181 indata: &mut [PulseCode],
182 data: &[PulseCode],
183 ) -> Result<usize, Error> {
184 if self.input.level() == Level::Low {
185 Err(Error::InputNotHigh)?;
186 }
187 // The master drives the bus (TX) while sampling it (RX) in the same time
188 // slots, so both must run concurrently: `join` arms RX first, then drives
189 // TX, and both complete once the line returns idle. A separate software
190 // timer bounds the wait so a stuck (never-idle) bus cannot hang forever —
191 // replacing the original TX-pulse timeout hack.
192 match select(
193 join(self.rx.receive(indata), self.tx.transmit(data)),
194 Timer::after(Self::RX_TIMEOUT),
195 )
196 .await
197 {
198 Either::First((rx_res, tx_res)) => {
199 tx_res.map_err(Error::SendError)?;
200 rx_res.map_err(Error::ReceiveError)
201 }
202 Either::Second(()) => Err(Error::ReceiveTimedOut),
203 }
204 }
205
206 /// Bus-low duration (µs) for a written '0' — a 1-Wire write-0 holds the line
207 /// low for 60–120 µs; 70 µs sits in that window.
208 const ZERO_BIT_LEN: u16 = 70;
209 /// Bus-low duration (µs) for a written '1' / read slot — a brief 1–15 µs low
210 /// that opens the slot before the line is released to be sampled.
211 const ONE_BIT_LEN: u16 = 3;
212 /// A read slot reads '1' when the captured bus-low is shorter than this many
213 /// µs (only the master's own opening pulse); a device signalling '0' holds
214 /// the line low well past it.
215 const READ_SAMPLE_THRESHOLD: u16 = 20;
216
217 /// Encode a single 1-Wire bit as an RMT pulse code (write/read time slot).
218 pub fn encode_bit(bit: bool) -> PulseCode {
219 if bit {
220 PulseCode::new(
221 Level::High,
222 Self::ONE_BIT_LEN,
223 Level::Low,
224 Self::ZERO_BIT_LEN,
225 )
226 } else {
227 PulseCode::new(
228 Level::High,
229 Self::ZERO_BIT_LEN,
230 Level::Low,
231 Self::ONE_BIT_LEN,
232 )
233 }
234 }
235
236 /// Decode a sampled RMT pulse code back into the 1-Wire bit value.
237 pub fn decode_bit(code: PulseCode) -> bool {
238 code.length1() < Self::READ_SAMPLE_THRESHOLD
239 }
240
241 /// Write one byte (LSB first) and read the byte the bus returns in the
242 /// same time slots.
243 pub async fn exchange_byte(&mut self, byte: u8) -> Result<u8, Error> {
244 // 8 bit-slots followed by a trailing end marker; sized 10 for headroom.
245 let mut data = [PulseCode::end_marker(); 10];
246 let mut indata = [PulseCode::end_marker(); 10];
247 for (n, slot) in data.iter_mut().take(8).enumerate() {
248 *slot = Self::encode_bit(byte & (1 << n) != 0);
249 }
250 let _res = self.send_and_receive(&mut indata, &data).await?;
251 let mut res: u8 = 0;
252 for (n, &code) in indata.iter().take(8).enumerate() {
253 if Self::decode_bit(code) {
254 res |= 1 << n;
255 }
256 }
257 Ok(res)
258 }
259
260 /// Write one byte (LSB first) without reading the response.
261 pub async fn send_byte(&mut self, byte: u8) -> Result<(), Error> {
262 let mut data = [PulseCode::end_marker(); 10];
263 for (n, slot) in data.iter_mut().take(8).enumerate() {
264 *slot = Self::encode_bit(byte & (1 << n) != 0);
265 }
266 self.tx.transmit(&data).await?;
267 Ok(())
268 }
269
270 /// Maximum number of bits a single [`OneWire::exchange_bits`] call accepts.
271 const MAX_EXCHANGE_BITS: usize = 8;
272
273 /// Write the bits in `bits` and read the bus response into `out` in the
274 /// same time slots. `bits` and `out` must have equal length, and at most
275 /// [`Self::MAX_EXCHANGE_BITS`] elements.
276 ///
277 /// This replaces the original const-generic `exchange_bits<const N>` (which
278 /// required `generic_const_exprs`) with a slice-based API backed by a small
279 /// fixed-capacity buffer. The RMT framing is identical: each bit maps to one
280 /// `PulseCode` followed by a trailing `end_marker()`.
281 pub async fn exchange_bits(&mut self, bits: &[bool], out: &mut [bool]) -> Result<(), Error> {
282 debug_assert_eq!(bits.len(), out.len());
283 debug_assert!(bits.len() <= Self::MAX_EXCHANGE_BITS);
284 let n_bits = bits.len();
285
286 // One PulseCode per bit, plus a trailing end_marker (pre-filled).
287 let mut data = [PulseCode::end_marker(); Self::MAX_EXCHANGE_BITS + 1];
288 let mut indata = [PulseCode::end_marker(); Self::MAX_EXCHANGE_BITS + 1];
289 for n in 0..n_bits {
290 data[n] = Self::encode_bit(bits[n]);
291 }
292 let _res = self
293 .send_and_receive(&mut indata[..n_bits + 1], &data[..n_bits + 1])
294 .await?;
295 for n in 0..n_bits {
296 out[n] = Self::decode_bit(indata[n]);
297 }
298 Ok(())
299 }
300
301 /// Write a 64-bit value (typically a ROM address) least-significant byte
302 /// first.
303 pub async fn send_u64(&mut self, val: u64) -> Result<(), Error> {
304 for byte in val.to_le_bytes() {
305 self.send_byte(byte).await?;
306 }
307 Ok(())
308 }
309
310 /// Write a 64-bit 1-Wire ROM [`Address`].
311 pub async fn send_address(&mut self, val: Address) -> Result<(), Error> {
312 self.send_u64(val.0).await
313 }
314}
315
316/// Errors returned by 1-Wire bus operations.
317#[derive(Debug, ThisError)]
318pub enum Error {
319 /// The bus was not idle-high before a transaction (missing pull-up?).
320 #[error("1-Wire bus was not idle-high before a transaction (missing pull-up?)")]
321 InputNotHigh,
322 /// No presence/response was sampled before the RX timeout elapsed.
323 #[error("no 1-Wire response sampled before the RX timeout")]
324 ReceiveTimedOut,
325 /// The RMT RX channel reported an error.
326 #[error("RMT RX channel error: {0:?}")]
327 ReceiveError(esp_hal::rmt::Error),
328 /// The RMT TX channel reported an error.
329 #[error("RMT TX channel error: {0:?}")]
330 SendError(esp_hal::rmt::Error),
331 /// An RMT channel could not be configured.
332 #[error("RMT channel configuration error: {0:?}")]
333 ConfigError(#[from] ConfigError),
334}
335
336// Two variants wrap `rmt::Error` (RX vs TX), so `#[from]` would be ambiguous;
337// a bare bus error is conventionally a send-side failure.
338impl From<esp_hal::rmt::Error> for Error {
339 fn from(e: esp_hal::rmt::Error) -> Error {
340 Error::SendError(e)
341 }
342}
343
344/// Dallas/Maxim 1-Wire CRC-8 (polynomial X^8 + X^5 + X^4 + 1, reflected 0x8C).
345///
346/// Used to validate ROM addresses (byte 7 covers bytes 0..7) and DS18B20
347/// scratchpad reads (byte 8 covers bytes 0..8). A correct frame CRCs to 0 when
348/// the trailing CRC byte is included; this helper returns the CRC of `data`, so
349/// callers compare it against the received CRC byte. See Maxim app note 27.
350pub fn crc8(data: &[u8]) -> u8 {
351 let mut crc = 0u8;
352 for &byte in data {
353 let mut b = byte;
354 for _ in 0..8 {
355 let mix = (crc ^ b) & 0x01;
356 crc >>= 1;
357 if mix != 0 {
358 crc ^= 0x8C;
359 }
360 b >>= 1;
361 }
362 }
363 crc
364}
365
366/// A 64-bit 1-Wire ROM address (family code, serial, CRC).
367#[derive(PartialEq, Eq, Clone, Copy, Hash)]
368pub struct Address(pub u64);
369
370// All three formats render the ROM byte-wise, family code first (the LSB of the
371// underlying u64), zero-padded so a leading-zero byte is never ambiguous.
372impl LowerHex for Address {
373 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
374 for byte in self.0.to_le_bytes() {
375 core::write!(f, "{:02x}", byte)?;
376 }
377 Ok(())
378 }
379}
380
381impl core::fmt::Display for Address {
382 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
383 for (i, byte) in self.0.to_le_bytes().iter().enumerate() {
384 if i > 0 {
385 core::write!(f, ":")?;
386 }
387 core::write!(f, "{:02X}", byte)?;
388 }
389 Ok(())
390 }
391}
392
393impl core::fmt::Debug for Address {
394 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
395 core::write!(f, "Address({})", self)
396 }
397}
398
399/// State machine for the 1-Wire ROM Search algorithm, enumerating every device
400/// address on the bus across repeated [`Search::next`] calls.
401pub struct Search {
402 command: u8,
403 address: u64,
404 #[cfg(feature = "search-masks")]
405 address_mask: u64,
406 last_discrepancy: Option<usize>,
407 complete: bool,
408}
409
410/// Errors returned while iterating a ROM [`Search`].
411#[derive(Debug, ThisError)]
412pub enum SearchError {
413 /// All devices have already been enumerated.
414 #[error("all devices have been enumerated")]
415 SearchComplete,
416 /// No device responded to the search.
417 #[error("no device responded to the search")]
418 NoDevicesPresent,
419 /// The enumerated ROM address failed its CRC-8 check (bus glitch). The
420 /// search state has still advanced, so a subsequent [`Search::next`] call
421 /// continues enumeration past the corrupt address.
422 #[error("enumerated ROM address failed its CRC-8 check")]
423 CrcMismatch,
424 /// An underlying bus error occurred.
425 #[error("1-Wire bus error during search: {0}")]
426 BusError(#[from] Error),
427}
428
429impl Search {
430 /// Start a normal (0xF0) ROM search over all devices on the bus.
431 pub fn new() -> Search {
432 Search {
433 command: 0xF0,
434 address: 0,
435 #[cfg(feature = "search-masks")]
436 address_mask: 0,
437 last_discrepancy: None,
438 complete: false,
439 }
440 }
441
442 /// Start an alarm (0xEC) search, enumerating only devices in an alarm state.
443 pub fn new_alarm() -> Search {
444 Search {
445 command: 0xEC,
446 address: 0,
447 #[cfg(feature = "search-masks")]
448 address_mask: 0,
449 last_discrepancy: None,
450 complete: false,
451 }
452 }
453
454 /// Start a search constrained to addresses matching `fixed_bits` under
455 /// `bit_mask`.
456 #[cfg(feature = "search-masks")]
457 pub fn new_with_mask(fixed_bits: u64, bit_mask: u64) -> Search {
458 Search {
459 command: 0xEC,
460 address: fixed_bits,
461 address_mask: bit_mask,
462 last_discrepancy: None,
463 complete: false,
464 }
465 }
466
467 /// Advance the search and return the next device [`Address`], or a
468 /// [`SearchError`] once enumeration finishes or the bus errors.
469 pub async fn next<'d>(&mut self, ow: &mut OneWire<'d>) -> Result<Address, SearchError> {
470 if self.complete {
471 return Err(SearchError::SearchComplete);
472 }
473 let have_devices = ow.reset().await?;
474 let mut last_zero = None;
475 ow.send_byte(self.command).await?;
476 if have_devices {
477 for id_bit_number in 0..64 {
478 let mut id_bits = [false; 2];
479 ow.exchange_bits(&[true, true], &mut id_bits).await?;
480 let search_direction = match id_bits {
481 #[cfg(feature = "search-masks")]
482 _ if self.address_mask & (1 << id_bit_number) != 0 => {
483 self.address & (1 << id_bit_number) != 0
484 }
485 [false, true] => false,
486 [true, false] => true,
487 [true, true] => {
488 return Err(SearchError::NoDevicesPresent);
489 }
490 [false, false] => {
491 if self.last_discrepancy == Some(id_bit_number) {
492 true
493 } else if Some(id_bit_number) > self.last_discrepancy {
494 last_zero = Some(id_bit_number);
495 false
496 } else {
497 self.address & (1 << id_bit_number) != 0
498 }
499 }
500 };
501 if search_direction {
502 self.address |= 1 << id_bit_number;
503 } else {
504 self.address &= !(1 << id_bit_number);
505 }
506 let mut sent = [false; 1];
507 ow.exchange_bits(&[search_direction], &mut sent).await?;
508 }
509 self.last_discrepancy = last_zero;
510 self.complete = last_zero.is_none();
511 // Byte 7 of the ROM is a CRC-8 over the family code + 48-bit serial
512 // (bytes 0..7). Reject a corrupt enumeration rather than handing the
513 // caller a bogus address; enumeration state has already advanced.
514 let rom = self.address.to_le_bytes();
515 if crc8(&rom[..7]) != rom[7] {
516 return Err(SearchError::CrcMismatch);
517 }
518 Ok(Address(self.address))
519 } else {
520 Err(SearchError::NoDevicesPresent)
521 }
522 }
523}
524
525impl Default for Search {
526 fn default() -> Self {
527 Self::new()
528 }
529}