aboutsummaryrefslogtreecommitdiff
path: root/embassy-embedded-hal/src/shared_bus/blocking/spi.rs
blob: 7d383980d832c25e7ddbb08f06542fa578ea9aa5 (plain)
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
//! Blocking shared SPI bus
//!
//! # Example (nrf52)
//!
//! ```rust,ignore
//! use embassy_embedded_hal::shared_bus::blocking::spi::SpiDevice;
//! use embassy_sync::blocking_mutex::{NoopMutex, raw::NoopRawMutex};
//!
//! static SPI_BUS: StaticCell<NoopMutex<RefCell<Spim<SPI3>>>> = StaticCell::new();
//! let spi = Spim::new_txonly(p.SPI3, Irqs, p.P0_15, p.P0_18, Config::default());
//! let spi_bus = NoopMutex::new(RefCell::new(spi));
//! let spi_bus = SPI_BUS.init(spi_bus);
//!
//! // Device 1, using embedded-hal compatible driver for ST7735 LCD display
//! let cs_pin1 = Output::new(p.P0_24, Level::Low, OutputDrive::Standard);
//! let spi_dev1 = SpiDevice::new(spi_bus, cs_pin1);
//! let display1 = ST7735::new(spi_dev1, dc1, rst1, Default::default(), false, 160, 128);
//! ```

use core::cell::RefCell;

use embassy_sync::blocking_mutex::raw::RawMutex;
use embassy_sync::blocking_mutex::Mutex;
use embedded_hal_1::digital::OutputPin;
use embedded_hal_1::spi::{self, Operation, SpiBus};

use crate::shared_bus::SpiDeviceError;
use crate::SetConfig;

/// SPI device on a shared bus.
pub struct SpiDevice<'a, M: RawMutex, BUS, CS, Word: Copy + 'static = u8> {
    bus: &'a Mutex<M, RefCell<BUS>>,
    cs: CS,
    _word: core::marker::PhantomData<Word>,
}

impl<'a, M: RawMutex, BUS, CS, Word: Copy + 'static> SpiDevice<'a, M, BUS, CS, Word> {
    /// Create a new `SpiDevice`.
    pub fn new(bus: &'a Mutex<M, RefCell<BUS>>, cs: CS) -> Self {
        Self {
            bus,
            cs,
            _word: core::marker::PhantomData,
        }
    }
}

impl<'a, M: RawMutex, BUS, CS, Word> spi::ErrorType for SpiDevice<'a, M, BUS, CS, Word>
where
    BUS: spi::ErrorType,
    CS: OutputPin,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BUS::Error, CS::Error>;
}

impl<BUS, M, CS, Word> embedded_hal_1::spi::SpiDevice<Word> for SpiDevice<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: SpiBus<Word>,
    CS: OutputPin,
    Word: Copy + 'static,
{
    fn transaction(&mut self, operations: &mut [embedded_hal_1::spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
            return Err(SpiDeviceError::DelayNotSupported);
        }

        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;

            let op_res = operations.iter_mut().try_for_each(|op| match op {
                Operation::Read(buf) => bus.read(buf),
                Operation::Write(buf) => bus.write(buf),
                Operation::Transfer(read, write) => bus.transfer(read, write),
                Operation::TransferInPlace(buf) => bus.transfer_in_place(buf),
                #[cfg(not(feature = "time"))]
                Operation::DelayNs(_) => unreachable!(),
                #[cfg(feature = "time")]
                Operation::DelayNs(ns) => {
                    embassy_time::block_for(embassy_time::Duration::from_nanos(*ns as _));
                    Ok(())
                }
            });

            // On failure, it's important to still flush and deassert CS.
            let flush_res = bus.flush();
            let cs_res = self.cs.set_high();

            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            flush_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;

            Ok(op_res)
        })
    }
}

impl<'d, M, BUS, CS, BusErr, CsErr, Word> embedded_hal_02::blocking::spi::Transfer<u8>
    for SpiDevice<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: embedded_hal_02::blocking::spi::Transfer<u8, Error = BusErr>,
    CS: OutputPin<Error = CsErr>,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BusErr, CsErr>;
    fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error> {
        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;
            let op_res = bus.transfer(words);
            let cs_res = self.cs.set_high();
            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;
            Ok(op_res)
        })
    }
}

impl<'d, M, BUS, CS, BusErr, CsErr, Word> embedded_hal_02::blocking::spi::Write<u8> for SpiDevice<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: embedded_hal_02::blocking::spi::Write<u8, Error = BusErr>,
    CS: OutputPin<Error = CsErr>,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BusErr, CsErr>;

    fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;
            let op_res = bus.write(words);
            let cs_res = self.cs.set_high();
            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;
            Ok(op_res)
        })
    }
}

impl<'d, M, BUS, CS, BusErr, CsErr, Word> embedded_hal_02::blocking::spi::Transfer<u16>
    for SpiDevice<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: embedded_hal_02::blocking::spi::Transfer<u16, Error = BusErr>,
    CS: OutputPin<Error = CsErr>,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BusErr, CsErr>;
    fn transfer<'w>(&mut self, words: &'w mut [u16]) -> Result<&'w [u16], Self::Error> {
        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;
            let op_res = bus.transfer(words);
            let cs_res = self.cs.set_high();
            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;
            Ok(op_res)
        })
    }
}

impl<'d, M, BUS, CS, BusErr, CsErr, Word> embedded_hal_02::blocking::spi::Write<u16> for SpiDevice<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: embedded_hal_02::blocking::spi::Write<u16, Error = BusErr>,
    CS: OutputPin<Error = CsErr>,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BusErr, CsErr>;

    fn write(&mut self, words: &[u16]) -> Result<(), Self::Error> {
        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;
            let op_res = bus.write(words);
            let cs_res = self.cs.set_high();
            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;
            Ok(op_res)
        })
    }
}

/// SPI device on a shared bus, with its own configuration.
///
/// This is like [`SpiDevice`], with an additional bus configuration that's applied
/// to the bus before each use using [`SetConfig`]. This allows different
/// devices on the same bus to use different communication settings.
pub struct SpiDeviceWithConfig<'a, M: RawMutex, BUS: SetConfig, CS, Word: Copy + 'static = u8> {
    bus: &'a Mutex<M, RefCell<BUS>>,
    cs: CS,
    config: BUS::Config,
    _word: core::marker::PhantomData<Word>,
}

impl<'a, M: RawMutex, BUS: SetConfig, CS, Word: Copy + 'static> SpiDeviceWithConfig<'a, M, BUS, CS, Word> {
    /// Create a new `SpiDeviceWithConfig`.
    pub fn new(bus: &'a Mutex<M, RefCell<BUS>>, cs: CS, config: BUS::Config) -> Self {
        Self {
            bus,
            cs,
            config,
            _word: core::marker::PhantomData,
        }
    }

    /// Change the device's config at runtime
    pub fn set_config(&mut self, config: BUS::Config) {
        self.config = config;
    }
}

impl<'a, M, BUS, CS, Word> spi::ErrorType for SpiDeviceWithConfig<'a, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: spi::ErrorType + SetConfig,
    CS: OutputPin,
    Word: Copy + 'static,
{
    type Error = SpiDeviceError<BUS::Error, CS::Error>;
}

impl<BUS, M, CS, Word> embedded_hal_1::spi::SpiDevice<Word> for SpiDeviceWithConfig<'_, M, BUS, CS, Word>
where
    M: RawMutex,
    BUS: SpiBus<Word> + SetConfig,
    CS: OutputPin,
    Word: Copy + 'static,
{
    fn transaction(&mut self, operations: &mut [embedded_hal_1::spi::Operation<'_, Word>]) -> Result<(), Self::Error> {
        if cfg!(not(feature = "time")) && operations.iter().any(|op| matches!(op, Operation::DelayNs(_))) {
            return Err(SpiDeviceError::DelayNotSupported);
        }

        self.bus.lock(|bus| {
            let mut bus = bus.borrow_mut();
            bus.set_config(&self.config).map_err(|_| SpiDeviceError::Config)?;
            self.cs.set_low().map_err(SpiDeviceError::Cs)?;

            let op_res = operations.iter_mut().try_for_each(|op| match op {
                Operation::Read(buf) => bus.read(buf),
                Operation::Write(buf) => bus.write(buf),
                Operation::Transfer(read, write) => bus.transfer(read, write),
                Operation::TransferInPlace(buf) => bus.transfer_in_place(buf),
                #[cfg(not(feature = "time"))]
                Operation::DelayNs(_) => unreachable!(),
                #[cfg(feature = "time")]
                Operation::DelayNs(ns) => {
                    embassy_time::block_for(embassy_time::Duration::from_nanos(*ns as _));
                    Ok(())
                }
            });

            // On failure, it's important to still flush and deassert CS.
            let flush_res = bus.flush();
            let cs_res = self.cs.set_high();

            let op_res = op_res.map_err(SpiDeviceError::Spi)?;
            flush_res.map_err(SpiDeviceError::Spi)?;
            cs_res.map_err(SpiDeviceError::Cs)?;
            Ok(op_res)
        })
    }
}