embassy_embedded_hal/shared_bus/asynch/
spi.rs

1//! Asynchronous shared SPI bus
2//!
3//! # Example (nrf52)
4//!
5//! ```rust,ignore
6//! use embassy_embedded_hal::shared_bus::spi::SpiDevice;
7//! use embassy_sync::mutex::Mutex;
8//! use embassy_sync::blocking_mutex::raw::NoopRawMutex;
9//!
10//! static SPI_BUS: StaticCell<Mutex<NoopRawMutex, spim::Spim<SPI3>>> = StaticCell::new();
11//! let mut config = spim::Config::default();
12//! config.frequency = spim::Frequency::M32;
13//! let spi = spim::Spim::new_txonly(p.SPI3, Irqs, p.P0_15, p.P0_18, config);
14//! let spi_bus = Mutex::new(spi);
15//! let spi_bus = SPI_BUS.init(spi_bus);
16//!
17//! // Device 1, using embedded-hal-async compatible driver for ST7735 LCD display
18//! let cs_pin1 = Output::new(p.P0_24, Level::Low, OutputDrive::Standard);
19//! let spi_dev1 = SpiDevice::new(spi_bus, cs_pin1);
20//! let display1 = ST7735::new(spi_dev1, dc1, rst1, Default::default(), 160, 128);
21//!
22//! // Device 2
23//! let cs_pin2 = Output::new(p.P0_24, Level::Low, OutputDrive::Standard);
24//! let spi_dev2 = SpiDevice::new(spi_bus, cs_pin2);
25//! let display2 = ST7735::new(spi_dev2, dc2, rst2, Default::default(), 160, 128);
26//! ```
27
28use embassy_hal_internal::drop::OnDrop;
29use embassy_sync::blocking_mutex::raw::RawMutex;
30use embassy_sync::mutex::Mutex;
31use embedded_hal_1::digital::OutputPin;
32use embedded_hal_1::spi::Operation;
33use embedded_hal_async::spi;
34
35use crate::shared_bus::SpiDeviceError;
36use crate::SetConfig;
37
38/// SPI device on a shared bus.
39pub struct SpiDevice<'a, M: RawMutex, BUS, CS> {
40    bus: &'a Mutex<M, BUS>,
41    cs: CS,
42}
43
44impl<'a, M: RawMutex, BUS, CS> SpiDevice<'a, M, BUS, CS> {
45    /// Create a new `SpiDevice`.
46    pub fn new(bus: &'a Mutex<M, BUS>, cs: CS) -> Self {
47        Self { bus, cs }
48    }
49}
50
51impl<'a, M: RawMutex, BUS, CS> spi::ErrorType for SpiDevice<'a, M, BUS, CS>
52where
53    BUS: spi::ErrorType,
54    CS: OutputPin,
55{
56    type Error = SpiDeviceError<BUS::Error, CS::Error>;
57}
58
59impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDevice<'_, M, BUS, CS>
60where
61    M: RawMutex,
62    BUS: spi::SpiBus<Word>,
63    CS: OutputPin,
64    Word: Copy + 'static,
65{
66    async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
67        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
68            return Err(SpiDeviceError::DelayNotSupported);
69        }
70
71        let mut bus = self.bus.lock().await;
72        self.cs.set_low().map_err(SpiDeviceError::Cs)?;
73
74        let cs_drop = OnDrop::new(|| {
75            // This drop guard deasserts CS pin if the async operation is cancelled.
76            // Errors are ignored in this drop handler, as there's nothing we can do about them.
77            // If the async operation is completed without cancellation, this handler will not
78            // be run, and the CS pin will be deasserted with proper error handling.
79            let _ = self.cs.set_high();
80        });
81
82        let op_res = 'ops: {
83            for op in operations {
84                let res = match op {
85                    Operation::Read(buf) => bus.read(buf).await,
86                    Operation::Write(buf) => bus.write(buf).await,
87                    Operation::Transfer(read, write) => bus.transfer(read, write).await,
88                    Operation::TransferInPlace(buf) => bus.transfer_in_place(buf).await,
89                    #[cfg(not(feature = "time"))]
90                    Operation::DelayNs(_) => unreachable!(),
91                    #[cfg(feature = "time")]
92                    Operation::DelayNs(ns) => match bus.flush().await {
93                        Err(e) => Err(e),
94                        Ok(()) => {
95                            embassy_time::Timer::after_nanos(*ns as _).await;
96                            Ok(())
97                        }
98                    },
99                };
100                if let Err(e) = res {
101                    break 'ops Err(e);
102                }
103            }
104            Ok(())
105        };
106
107        // On failure, it's important to still flush and deassert CS.
108        let flush_res = bus.flush().await;
109
110        // Now that all the async operations are done, we defuse the CS guard,
111        // and manually set the CS pin low (to better handle the possible errors).
112        cs_drop.defuse();
113        let cs_res = self.cs.set_high();
114
115        let op_res = op_res.map_err(SpiDeviceError::Spi)?;
116        flush_res.map_err(SpiDeviceError::Spi)?;
117        cs_res.map_err(SpiDeviceError::Cs)?;
118
119        Ok(op_res)
120    }
121}
122
123/// SPI device on a shared bus, with its own configuration.
124///
125/// This is like [`SpiDevice`], with an additional bus configuration that's applied
126/// to the bus before each use using [`SetConfig`]. This allows different
127/// devices on the same bus to use different communication settings.
128pub struct SpiDeviceWithConfig<'a, M: RawMutex, BUS: SetConfig, CS> {
129    bus: &'a Mutex<M, BUS>,
130    cs: CS,
131    config: BUS::Config,
132}
133
134impl<'a, M: RawMutex, BUS: SetConfig, CS> SpiDeviceWithConfig<'a, M, BUS, CS> {
135    /// Create a new `SpiDeviceWithConfig`.
136    pub fn new(bus: &'a Mutex<M, BUS>, cs: CS, config: BUS::Config) -> Self {
137        Self { bus, cs, config }
138    }
139
140    /// Change the device's config at runtime
141    pub fn set_config(&mut self, config: BUS::Config) {
142        self.config = config;
143    }
144}
145
146impl<'a, M, BUS, CS> spi::ErrorType for SpiDeviceWithConfig<'a, M, BUS, CS>
147where
148    BUS: spi::ErrorType + SetConfig,
149    CS: OutputPin,
150    M: RawMutex,
151{
152    type Error = SpiDeviceError<BUS::Error, CS::Error>;
153}
154
155impl<M, BUS, CS, Word> spi::SpiDevice<Word> for SpiDeviceWithConfig<'_, M, BUS, CS>
156where
157    M: RawMutex,
158    BUS: spi::SpiBus<Word> + SetConfig,
159    CS: OutputPin,
160    Word: Copy + 'static,
161{
162    async fn transaction(&mut self, operations: &mut [spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
163        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
164            return Err(SpiDeviceError::DelayNotSupported);
165        }
166
167        let mut bus = self.bus.lock().await;
168        bus.set_config(&self.config).map_err(|_| SpiDeviceError::Config)?;
169        self.cs.set_low().map_err(SpiDeviceError::Cs)?;
170
171        let cs_drop = OnDrop::new(|| {
172            // Please see comment in SpiDevice for an explanation of this drop handler.
173            let _ = self.cs.set_high();
174        });
175
176        let op_res = 'ops: {
177            for op in operations {
178                let res = match op {
179                    Operation::Read(buf) => bus.read(buf).await,
180                    Operation::Write(buf) => bus.write(buf).await,
181                    Operation::Transfer(read, write) => bus.transfer(read, write).await,
182                    Operation::TransferInPlace(buf) => bus.transfer_in_place(buf).await,
183                    #[cfg(not(feature = "time"))]
184                    Operation::DelayNs(_) => unreachable!(),
185                    #[cfg(feature = "time")]
186                    Operation::DelayNs(ns) => match bus.flush().await {
187                        Err(e) => Err(e),
188                        Ok(()) => {
189                            embassy_time::Timer::after_nanos(*ns as _).await;
190                            Ok(())
191                        }
192                    },
193                };
194                if let Err(e) = res {
195                    break 'ops Err(e);
196                }
197            }
198            Ok(())
199        };
200
201        // On failure, it's important to still flush and deassert CS.
202        let flush_res = bus.flush().await;
203        cs_drop.defuse();
204        let cs_res = self.cs.set_high();
205
206        let op_res = op_res.map_err(SpiDeviceError::Spi)?;
207        flush_res.map_err(SpiDeviceError::Spi)?;
208        cs_res.map_err(SpiDeviceError::Cs)?;
209
210        Ok(op_res)
211    }
212}