embedded_hal_bus/spi/
mod.rs

1//! `SpiDevice` implementations.
2
3use core::fmt::{self, Debug, Display, Formatter};
4use embedded_hal::spi::{Error, ErrorKind};
5
6mod exclusive;
7pub use exclusive::*;
8mod refcell;
9pub use refcell::*;
10#[cfg(feature = "std")]
11mod mutex;
12#[cfg(feature = "std")]
13pub use mutex::*;
14mod atomic;
15mod critical_section;
16mod shared;
17pub use atomic::*;
18
19pub use self::critical_section::*;
20
21#[cfg(feature = "defmt-03")]
22use crate::defmt;
23
24/// Error type for [`ExclusiveDevice`] operations.
25#[derive(Copy, Clone, Eq, PartialEq, Debug)]
26#[cfg_attr(feature = "defmt-03", derive(defmt::Format))]
27pub enum DeviceError<BUS, CS> {
28    /// An inner SPI bus operation failed.
29    Spi(BUS),
30    /// Asserting or deasserting CS failed.
31    Cs(CS),
32}
33
34impl<BUS: Display, CS: Display> Display for DeviceError<BUS, CS> {
35    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
36        match self {
37            Self::Spi(bus) => write!(f, "SPI bus error: {}", bus),
38            Self::Cs(cs) => write!(f, "SPI CS error: {}", cs),
39        }
40    }
41}
42
43#[cfg(feature = "std")]
44impl<BUS: Debug + Display, CS: Debug + Display> std::error::Error for DeviceError<BUS, CS> {}
45
46impl<BUS, CS> Error for DeviceError<BUS, CS>
47where
48    BUS: Error + Debug,
49    CS: Debug,
50{
51    #[inline]
52    fn kind(&self) -> ErrorKind {
53        match self {
54            Self::Spi(e) => e.kind(),
55            Self::Cs(_) => ErrorKind::ChipSelectFault,
56        }
57    }
58}
59
60/// Dummy [`DelayNs`](embedded_hal::delay::DelayNs) implementation that panics on use.
61#[derive(Copy, Clone, Eq, PartialEq, Debug)]
62#[cfg_attr(feature = "defmt-03", derive(defmt::Format))]
63pub struct NoDelay;
64
65#[cold]
66fn no_delay_panic() {
67    panic!("You've tried to execute a SPI transaction containing a `Operation::DelayNs` in a `SpiDevice` created with `new_no_delay()`. Create it with `new()` instead, passing a `DelayNs` implementation.");
68}
69
70impl embedded_hal::delay::DelayNs for NoDelay {
71    #[inline]
72    fn delay_ns(&mut self, _ns: u32) {
73        no_delay_panic();
74    }
75}
76
77#[cfg(feature = "async")]
78#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
79impl embedded_hal_async::delay::DelayNs for NoDelay {
80    #[inline]
81    async fn delay_ns(&mut self, _ns: u32) {
82        no_delay_panic();
83    }
84}