Skip to main content

ch32_hal/
spi.rs

1//! SPI, Serial Peripheral Interface
2//!
3//! Capabilities:
4//!
5//! Master-mode transfers with software NSS and caller-managed chip select.
6//! Supports 8/16-bit words, all four clock modes, blocking and DMA transfers,
7//! and MSB/LSB first (MSB first only on CH32V003). The maximum serial clock is
8//! half the peripheral bus clock.
9
10use core::future::poll_fn;
11use core::marker::PhantomData;
12use core::ptr;
13use core::task::Poll;
14
15use embassy_futures::join::join;
16#[cfg(spi_v4x7)]
17use embassy_futures::select::{select, Either};
18use embassy_sync::waitqueue::AtomicWaker;
19use embedded_hal::spi::{Mode, Phase, Polarity, MODE_0};
20use pac::spi::vals::BaudRate;
21use pac::spi::Spi as Regs;
22
23use crate::dma::{slice_ptr_parts, word, ChannelAndRequest};
24use crate::gpio::{AfType, AnyPin, OutputType, Pull, Speed};
25use crate::internal::drop::OnDrop;
26use crate::mode::{Async, Blocking, Mode as PeriMode};
27use crate::time::Hertz;
28use crate::{interrupt, pac, peripherals, Peri};
29
30/// SPI error interrupt handler.
31pub struct InterruptHandler<T: Instance>(PhantomData<T>);
32
33impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
34    unsafe fn on_interrupt() {
35        if check_error_flags(&T::REGS.statr().read()).is_err() {
36            T::REGS.ctlr2().modify(|w| {
37                w.set_errie(false);
38                w.set_txdmaen(false);
39                w.set_rxdmaen(false);
40            });
41            T::state().waker.wake();
42        }
43    }
44}
45
46// the ring runs on the BDMA-style channels' circular transfers
47#[cfg(not(dma_v4x7))]
48mod slave;
49#[cfg(not(dma_v4x7))]
50pub use slave::{Half, SlaveConfig, SlaveError, SpiSlaveRing};
51
52/// SPI Error
53#[derive(Debug, PartialEq, Eq)]
54#[cfg_attr(feature = "defmt", derive(defmt::Format))]
55pub enum Error {
56    /// Invalid framing.
57    Framing,
58    /// CRC error (only if hardware CRC checking is enabled).
59    Crc,
60    /// Mode fault
61    ModeFault,
62    /// Overrun.
63    Overrun,
64    /// Buffer exceeds the DMA transfer counter.
65    BufferTooLong,
66    /// The constructor did not provide the required pins or DMA channel.
67    UnsupportedOperation,
68}
69
70#[derive(Copy, Clone, PartialEq, Eq)]
71pub enum BitOrder {
72    // CH32V003 supports MSB first only
73    #[cfg(not(spi_v0))]
74    LsbFirst,
75    MsbFirst,
76}
77
78#[non_exhaustive]
79#[derive(Copy, Clone)]
80pub struct Config {
81    pub mode: Mode,
82    pub bit_order: BitOrder,
83    pub frequency: Hertz,
84}
85
86impl Default for Config {
87    fn default() -> Self {
88        Self {
89            mode: MODE_0,
90            bit_order: BitOrder::MsbFirst,
91            frequency: Hertz::hz(1_000_000),
92        }
93    }
94}
95
96impl Config {
97    // CPHA
98    fn raw_phase(&self) -> bool {
99        match self.mode.phase {
100            Phase::CaptureOnSecondTransition => true,
101            Phase::CaptureOnFirstTransition => false,
102        }
103    }
104
105    // CPOL
106    fn raw_polarity(&self) -> bool {
107        match self.mode.polarity {
108            Polarity::IdleLow => false,
109            Polarity::IdleHigh => true,
110        }
111    }
112
113    fn lsb_first(&self) -> bool {
114        match self.bit_order {
115            #[cfg(not(spi_v0))]
116            BitOrder::LsbFirst => true,
117            BitOrder::MsbFirst => false,
118        }
119    }
120
121    fn from_cfgr(cfgr: &pac::spi::regs::Ctlr1, bus_clk: Hertz) -> Self {
122        let polarity = if cfgr.cpol() {
123            Polarity::IdleHigh
124        } else {
125            Polarity::IdleLow
126        };
127        let phase = if cfgr.cpha() {
128            Phase::CaptureOnSecondTransition
129        } else {
130            Phase::CaptureOnFirstTransition
131        };
132
133        let bit_order = match cfgr.lsbfirst() {
134            #[cfg(spi_v0)]
135            _ => BitOrder::MsbFirst,
136            #[cfg(not(spi_v0))]
137            true => BitOrder::LsbFirst,
138            #[cfg(not(spi_v0))]
139            false => BitOrder::MsbFirst,
140        };
141
142        let mode = Mode { polarity, phase };
143
144        let spi_freq = match cfgr.br() {
145            BaudRate::DIV_2 => bus_clk / 2_u32,
146            BaudRate::DIV_4 => bus_clk / 4_u32,
147            BaudRate::DIV_8 => bus_clk / 8_u32,
148            BaudRate::DIV_16 => bus_clk / 16_u32,
149            BaudRate::DIV_32 => bus_clk / 32_u32,
150            BaudRate::DIV_64 => bus_clk / 64_u32,
151            BaudRate::DIV_128 => bus_clk / 128_u32,
152            BaudRate::DIV_256 => bus_clk / 256_u32,
153        };
154
155        Self {
156            mode,
157            bit_order,
158            frequency: spi_freq,
159        }
160    }
161}
162
163/// SPI driver.
164pub struct Spi<'d, T: Instance, M: PeriMode> {
165    _peri: Peri<'d, T>,
166    sck: Option<Peri<'d, AnyPin>>,
167    mosi: Option<Peri<'d, AnyPin>>,
168    miso: Option<Peri<'d, AnyPin>>,
169    tx_dma: Option<ChannelAndRequest<'d>>,
170    rx_dma: Option<ChannelAndRequest<'d>>,
171    _phantom: PhantomData<M>,
172    current_word_size: word_impl::Config,
173}
174
175impl<'d, T: Instance, M: PeriMode> Spi<'d, T, M> {
176    fn new_inner(
177        peri: Peri<'d, T>,
178        sck: Option<Peri<'d, AnyPin>>,
179        mosi: Option<Peri<'d, AnyPin>>,
180        miso: Option<Peri<'d, AnyPin>>,
181        tx_dma: Option<ChannelAndRequest<'d>>,
182        rx_dma: Option<ChannelAndRequest<'d>>,
183        config: Config,
184    ) -> Self {
185        let regs = T::REGS;
186
187        // Frequencies below `clock / 256` are unrepresentable. Clamping to the
188        // slowest divisor matches the historical behavior of the existing
189        // families instead of panicking the constructor.
190        let div = calculate_baud_rate(T::frequency().0, config.frequency.0).unwrap_or(BaudRate::DIV_256);
191
192        let cpha = config.raw_phase();
193        let cpol = config.raw_polarity();
194
195        T::enable_and_reset();
196
197        configure_high_speed(regs, T::frequency().0, div, miso.is_some());
198
199        regs.ctlr2().modify(|w| w.set_ssoe(false));
200        regs.ctlr1().modify(|w| {
201            w.set_cpol(cpol);
202            w.set_cpha(cpha);
203            w.set_mstr(true); // master
204            w.set_br(div);
205            w.set_spe(false);
206            w.set_lsbfirst(config.lsb_first());
207            w.set_ssi(true);
208            w.set_ssm(true);
209            w.set_crcen(false);
210            w.set_bidimode(false); // undirectional
211            w.set_rxonly(false);
212            w.set_dff(false); // u8
213        });
214        #[cfg(spi_v4x7)]
215        if tx_dma.is_some() || rx_dma.is_some() {
216            use crate::interrupt::typelevel::Interrupt;
217            T::Interrupt::unpend();
218            unsafe { T::Interrupt::enable() };
219        }
220
221        Self {
222            _peri: peri,
223            sck,
224            mosi,
225            miso,
226            tx_dma,
227            rx_dma,
228            current_word_size: <u8 as SealedWord>::CONFIG,
229            _phantom: PhantomData,
230        }
231    }
232
233    /// Reconfigure the SPI peripheral.
234    pub fn set_config(&mut self, config: &Config) -> Result<(), ()> {
235        let cpha = config.raw_phase();
236        let cpol = config.raw_polarity();
237
238        let lsbfirst = config.lsb_first();
239
240        // Same clamping policy as the constructor.
241        let br = calculate_baud_rate(T::frequency().0, config.frequency.0).unwrap_or(BaudRate::DIV_256);
242        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
243        self.blocking_flush().map_err(|_| ())?;
244        T::REGS.ctlr1().modify(|w| w.set_spe(false));
245        configure_high_speed(T::REGS, T::frequency().0, br, self.miso.is_some());
246
247        T::REGS.ctlr1().modify(|w| {
248            w.set_cpol(cpol);
249            w.set_cpha(cpha);
250            w.set_br(br);
251            w.set_lsbfirst(lsbfirst);
252        });
253
254        Ok(())
255    }
256
257    /// Get current SPI configuration. Useful for get the current baudrate.
258    pub fn get_current_config(&self) -> Config {
259        let bus_freq = T::frequency();
260
261        Config::from_cfgr(&T::REGS.ctlr1().read(), bus_freq)
262    }
263
264    fn set_word_size(&mut self, config: word_impl::Config) {
265        if self.current_word_size == config {
266            return;
267        }
268        T::REGS.ctlr1().modify(|w| {
269            w.set_dff(config == <u16 as SealedWord>::CONFIG);
270        });
271        self.current_word_size = config;
272    }
273
274    fn prepare<W: Word>(&mut self, transmit_only: bool) -> Result<(), Error> {
275        self.blocking_flush()?;
276        T::REGS.ctlr1().modify(|w| w.set_spe(false));
277        flush_rx_fifo(T::REGS);
278        self.set_word_size(W::CONFIG);
279        T::REGS.ctlr1().modify(|w| {
280            w.set_mstr(true);
281            w.set_ssm(true);
282            w.set_ssi(true);
283            w.set_bidimode(transmit_only);
284            w.set_bidioe(transmit_only);
285            w.set_rxonly(false);
286        });
287        Ok(())
288    }
289
290    /// Wait for the final bit to leave the peripheral.
291    pub fn blocking_flush(&mut self) -> Result<(), Error> {
292        // A disabled peripheral has no transfer in flight. On CH32V4x7
293        // STATR.TXE reads 0 while SPE=0 (measured on CH32V467), so polling it
294        // before the first `prepare` enabled SPE would never complete.
295        if !T::REGS.ctlr1().read().spe() {
296            return Ok(());
297        }
298        loop {
299            let status = T::REGS.statr().read();
300            if let Err(error) = check_error_flags(&status) {
301                cleanup(T::REGS);
302                return Err(error);
303            }
304            if status.txe() && !status.bsy() {
305                return Ok(());
306            }
307        }
308    }
309
310    /// Blocking write.
311    pub fn blocking_write<W: Word>(&mut self, words: &[W]) -> Result<(), Error> {
312        if words.is_empty() {
313            return Ok(());
314        }
315        if self.mosi.is_none() {
316            return Err(Error::UnsupportedOperation);
317        }
318        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
319        self.prepare::<W>(true)?;
320        T::REGS.ctlr1().modify(|w| w.set_spe(true));
321        for word in words {
322            spin_until_tx_ready(&T::REGS)?;
323            unsafe {
324                ptr::write_volatile(T::REGS.datar().as_ptr().cast(), *word);
325            }
326        }
327        self.blocking_flush()
328    }
329
330    /// Blocking read, generating exactly one frame of clocks per word.
331    pub fn blocking_read<W: Word>(&mut self, words: &mut [W]) -> Result<(), Error> {
332        if words.is_empty() {
333            return Ok(());
334        }
335        if self.miso.is_none() {
336            return Err(Error::UnsupportedOperation);
337        }
338        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
339        self.prepare::<W>(false)?;
340        T::REGS.ctlr1().modify(|w| w.set_spe(true));
341        for word in words {
342            *word = transfer_word(&T::REGS, W::default())?;
343        }
344        self.blocking_flush()
345    }
346
347    /// Blocking transfer using the same buffer for transmit and receive.
348    pub fn blocking_transfer_in_place<W: Word>(&mut self, words: &mut [W]) -> Result<(), Error> {
349        if words.is_empty() {
350            return Ok(());
351        }
352        if self.mosi.is_none() || self.miso.is_none() {
353            return Err(Error::UnsupportedOperation);
354        }
355        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
356        self.prepare::<W>(false)?;
357        T::REGS.ctlr1().modify(|w| w.set_spe(true));
358        for word in words {
359            *word = transfer_word(&T::REGS, *word)?;
360        }
361        self.blocking_flush()
362    }
363
364    /// Blocking transfer of `max(read.len(), write.len())` words.
365    ///
366    /// Missing transmit words are zero; extra received words are discarded.
367    pub fn blocking_transfer<W: Word>(&mut self, read: &mut [W], write: &[W]) -> Result<(), Error> {
368        let length = read.len().max(write.len());
369        if length == 0 {
370            return Ok(());
371        }
372        if (!read.is_empty() && self.miso.is_none()) || (!write.is_empty() && self.mosi.is_none()) {
373            return Err(Error::UnsupportedOperation);
374        }
375        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
376        self.prepare::<W>(false)?;
377        T::REGS.ctlr1().modify(|w| w.set_spe(true));
378        for index in 0..length {
379            let sent = write.get(index).copied().unwrap_or_default();
380            let received = transfer_word(&T::REGS, sent)?;
381            if let Some(destination) = read.get_mut(index) {
382                *destination = received;
383            }
384        }
385        self.blocking_flush()
386    }
387}
388
389impl<'d, T: Instance> Spi<'d, T, Blocking> {
390    /// Create a new SPI driver.
391    pub fn new_blocking<#[cfg(not(afio_h4))] const REMAP: u8>(
392        peri: Peri<'d, T>,
393        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
394        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
395        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
396        config: Config,
397    ) -> Self {
398        apply_remap!();
399
400        Self::new_inner(
401            peri,
402            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
403            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
404            new_pin!(miso, AfType::input(Pull::None)),
405            None,
406            None,
407            config,
408        )
409    }
410
411    /// Create a new SPI driver, in RX-only mode (only MISO pin, no MOSI).
412    pub fn new_blocking_rxonly<#[cfg(not(afio_h4))] const REMAP: u8>(
413        peri: Peri<'d, T>,
414        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
415        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
416        config: Config,
417    ) -> Self {
418        apply_remap!();
419
420        Self::new_inner(
421            peri,
422            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
423            None,
424            new_pin!(miso, AfType::input(Pull::None)),
425            None,
426            None,
427            config,
428        )
429    }
430
431    /// Create a new SPI driver, in TX-only mode (only MOSI pin, no MISO).
432    pub fn new_blocking_txonly<#[cfg(not(afio_h4))] const REMAP: u8>(
433        peri: Peri<'d, T>,
434        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
435        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
436        config: Config,
437    ) -> Self {
438        apply_remap!();
439
440        Self::new_inner(
441            peri,
442            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
443            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
444            None,
445            None,
446            None,
447            config,
448        )
449    }
450
451    /// Create a new SPI driver, in TX-only mode, without SCK pin.
452    ///
453    /// This can be useful for bit-banging non-SPI protocols.
454    pub fn new_blocking_txonly_nosck<#[cfg(not(afio_h4))] const REMAP: u8>(
455        peri: Peri<'d, T>,
456        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
457        config: Config,
458    ) -> Self {
459        apply_remap!();
460
461        Self::new_inner(
462            peri,
463            None,
464            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
465            None,
466            None,
467            None,
468            config,
469        )
470    }
471}
472
473impl<'d, T: Instance> Spi<'d, T, Async> {
474    /// Create a new SPI driver.
475    pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
476        peri: Peri<'d, T>,
477        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
478        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
479        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
480        #[cfg(spi_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>,
481        tx_dma: Peri<'d, impl TxDma<T>>,
482        rx_dma: Peri<'d, impl RxDma<T>>,
483        config: Config,
484    ) -> Self {
485        apply_remap!();
486
487        Self::new_inner(
488            peri,
489            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
490            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
491            new_pin!(miso, AfType::input(Pull::None)),
492            new_dma!(tx_dma),
493            new_dma!(rx_dma),
494            config,
495        )
496    }
497
498    /// Create a new SPI driver, in RX-only mode (only MISO pin, no MOSI).
499    pub fn new_rxonly<#[cfg(not(afio_h4))] const REMAP: u8>(
500        peri: Peri<'d, T>,
501        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
502        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
503        #[cfg(spi_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>,
504        rx_dma: Peri<'d, impl RxDma<T>>,
505        config: Config,
506    ) -> Self {
507        apply_remap!();
508
509        Self::new_inner(
510            peri,
511            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
512            None,
513            new_pin!(miso, AfType::input(Pull::None)),
514            None,
515            new_dma!(rx_dma),
516            config,
517        )
518    }
519
520    /// Create a receive-only driver with DMA-generated dummy transmit words.
521    pub fn new_rxonly_with_tx_dma<#[cfg(not(afio_h4))] const REMAP: u8>(
522        peri: Peri<'d, T>,
523        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
524        miso: Peri<'d, if_remap!(impl MisoPin<T, REMAP>)>,
525        #[cfg(spi_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>,
526        tx_dma: Peri<'d, impl TxDma<T>>,
527        rx_dma: Peri<'d, impl RxDma<T>>,
528        config: Config,
529    ) -> Self {
530        apply_remap!();
531        Self::new_inner(
532            peri,
533            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
534            None,
535            new_pin!(miso, AfType::input(Pull::None)),
536            new_dma!(tx_dma),
537            new_dma!(rx_dma),
538            config,
539        )
540    }
541
542    /// Create a new SPI driver, in TX-only mode (only MOSI pin, no MISO).
543    pub fn new_txonly<#[cfg(not(afio_h4))] const REMAP: u8>(
544        peri: Peri<'d, T>,
545        sck: Peri<'d, if_remap!(impl SckPin<T, REMAP>)>,
546        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
547        #[cfg(spi_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>,
548        tx_dma: Peri<'d, impl TxDma<T>>,
549        config: Config,
550    ) -> Self {
551        apply_remap!();
552
553        Self::new_inner(
554            peri,
555            new_pin!(sck, AfType::output(OutputType::PushPull, Speed::High)),
556            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
557            None,
558            new_dma!(tx_dma),
559            None,
560            config,
561        )
562    }
563
564    /// Create a new SPI driver, in TX-only mode, without SCK pin.
565    ///
566    /// This can be useful for bit-banging non-SPI protocols.
567    pub fn new_txonly_nosck<#[cfg(not(afio_h4))] const REMAP: u8>(
568        peri: Peri<'d, T>,
569        mosi: Peri<'d, if_remap!(impl MosiPin<T, REMAP>)>,
570        #[cfg(spi_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>>,
571        tx_dma: Peri<'d, impl TxDma<T>>,
572        config: Config,
573    ) -> Self {
574        apply_remap!();
575
576        Self::new_inner(
577            peri,
578            None,
579            new_pin!(mosi, AfType::output(OutputType::PushPull, Speed::High)),
580            None,
581            new_dma!(tx_dma),
582            None,
583            config,
584        )
585    }
586
587    // Only CH32V4x7 has an SPI error interrupt binding in the constructors.
588    // Polling this future on the other families would wake the executor
589    // continuously for the whole DMA transfer, so they await the transfer and
590    // check the error flags once afterwards instead.
591    #[cfg(spi_v4x7)]
592    async fn wait_error() -> Error {
593        poll_fn(|cx| {
594            T::state().waker.register(cx.waker());
595            if let Err(error) = check_error_flags(&T::REGS.statr().read()) {
596                return Poll::Ready(error);
597            }
598            T::REGS.ctlr2().modify(|w| w.set_errie(true));
599            Poll::Pending
600        })
601        .await
602    }
603
604    /// Wait until the transmit buffer and shift register are empty.
605    pub async fn flush(&mut self) -> Result<(), Error> {
606        // Same boundary as `blocking_flush`: while SPE=0 the CH32V4x7 TXE
607        // flag is not meaningful, and no transfer can be in flight.
608        if !T::REGS.ctlr1().read().spe() {
609            return Ok(());
610        }
611        poll_fn(|cx| {
612            let status = T::REGS.statr().read();
613            if let Err(error) = check_error_flags(&status) {
614                cleanup(T::REGS);
615                return Poll::Ready(Err(error));
616            }
617            if status.txe() && !status.bsy() {
618                Poll::Ready(Ok(()))
619            } else {
620                cx.waker().wake_by_ref();
621                Poll::Pending
622            }
623        })
624        .await
625    }
626
627    /// Write using DMA; received data is ignored in transmit-only hardware mode.
628    pub async fn write<W: Word>(&mut self, data: &[W]) -> Result<(), Error> {
629        if data.is_empty() {
630            return Ok(());
631        }
632        if data.len() > u16::MAX as usize {
633            return Err(Error::BufferTooLong);
634        }
635        if self.mosi.is_none() || self.tx_dma.is_none() {
636            return Err(Error::UnsupportedOperation);
637        }
638        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
639        self.prepare::<W>(true)?;
640        let transfer = unsafe {
641            self.tx_dma
642                .as_mut()
643                .unwrap()
644                .write(data, T::REGS.datar().as_ptr().cast(), Default::default())
645        };
646        T::REGS.ctlr2().modify(|w| w.set_txdmaen(true));
647        T::REGS.ctlr1().modify(|w| w.set_spe(true));
648        #[cfg(spi_v4x7)]
649        if let Either::First(error) = select(Self::wait_error(), transfer).await {
650            return Err(error);
651        }
652        #[cfg(not(spi_v4x7))]
653        transfer.await;
654        self.flush().await
655    }
656
657    /// Read using DMA and exactly one frame of clocks per word.
658    ///
659    /// RX-only constructors generate dummy transmit words in software. Supply
660    /// both DMA channels with `new_rxonly_with_tx_dma` for DMA clock generation.
661    pub async fn read<W: Word>(&mut self, data: &mut [W]) -> Result<(), Error> {
662        if data.is_empty() {
663            return Ok(());
664        }
665        if data.len() > u16::MAX as usize {
666            return Err(Error::BufferTooLong);
667        }
668        if self.miso.is_none() || self.rx_dma.is_none() {
669            return Err(Error::UnsupportedOperation);
670        }
671        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
672        self.prepare::<W>(false)?;
673        let count = data.len();
674        let dummy = W::default();
675        let receive = unsafe {
676            self.rx_dma
677                .as_mut()
678                .unwrap()
679                .read(T::REGS.datar().as_ptr().cast(), data, Default::default())
680        };
681        if let Some(transmit) = self.tx_dma.as_mut() {
682            let transmit =
683                unsafe { transmit.write_repeated(&dummy, count, T::REGS.datar().as_ptr().cast(), Default::default()) };
684            T::REGS.ctlr2().modify(|w| {
685                w.set_rxdmaen(true);
686                w.set_txdmaen(true);
687            });
688            T::REGS.ctlr1().modify(|w| w.set_spe(true));
689            #[cfg(spi_v4x7)]
690            if let Either::First(error) = select(Self::wait_error(), join(transmit, receive)).await {
691                return Err(error);
692            }
693            #[cfg(not(spi_v4x7))]
694            join(transmit, receive).await;
695        } else {
696            let mut sent = 0;
697            let transmit = poll_fn(|cx| {
698                if T::REGS.statr().read().txe() {
699                    unsafe {
700                        ptr::write_volatile(T::REGS.datar().as_ptr().cast(), dummy);
701                    }
702                    sent += 1;
703                }
704                if sent == count {
705                    Poll::Ready(())
706                } else {
707                    cx.waker().wake_by_ref();
708                    Poll::Pending
709                }
710            });
711            T::REGS.ctlr2().modify(|w| w.set_rxdmaen(true));
712            T::REGS.ctlr1().modify(|w| w.set_spe(true));
713            #[cfg(spi_v4x7)]
714            if let Either::First(error) = select(Self::wait_error(), join(transmit, receive)).await {
715                return Err(error);
716            }
717            #[cfg(not(spi_v4x7))]
718            join(transmit, receive).await;
719        }
720        self.flush().await
721    }
722
723    async fn transfer_inner<W: Word>(&mut self, read: *mut [W], write: *const [W]) -> Result<(), Error> {
724        let (_, length) = slice_ptr_parts(read);
725        let (_, sent) = slice_ptr_parts(write);
726        assert_eq!(length, sent);
727        if length == 0 {
728            return Ok(());
729        }
730        if length > u16::MAX as usize {
731            return Err(Error::BufferTooLong);
732        }
733        if self.tx_dma.is_none() || self.rx_dma.is_none() {
734            return Err(Error::UnsupportedOperation);
735        }
736        let _cleanup = OnDrop::new(|| cleanup(T::REGS));
737        self.prepare::<W>(false)?;
738        let receive = unsafe {
739            self.rx_dma
740                .as_mut()
741                .unwrap()
742                .read_raw(T::REGS.datar().as_ptr().cast(), read, Default::default())
743        };
744        let transmit = unsafe {
745            self.tx_dma
746                .as_mut()
747                .unwrap()
748                .write_raw(write, T::REGS.datar().as_ptr().cast(), Default::default())
749        };
750        T::REGS.ctlr2().modify(|w| {
751            w.set_rxdmaen(true);
752            w.set_txdmaen(true);
753        });
754        T::REGS.ctlr1().modify(|w| w.set_spe(true));
755        #[cfg(spi_v4x7)]
756        if let Either::First(error) = select(Self::wait_error(), join(transmit, receive)).await {
757            return Err(error);
758        }
759        #[cfg(not(spi_v4x7))]
760        join(transmit, receive).await;
761        self.flush().await
762    }
763
764    /// Transfer `max(read.len(), write.len())` words using DMA.
765    ///
766    /// Missing transmit words are zero; extra received words are discarded.
767    pub async fn transfer<W: Word>(&mut self, read: &mut [W], write: &[W]) -> Result<(), Error> {
768        if read.len().max(write.len()) > u16::MAX as usize {
769            return Err(Error::BufferTooLong);
770        }
771        if (!read.is_empty() && self.miso.is_none()) || (!write.is_empty() && self.mosi.is_none()) {
772            return Err(Error::UnsupportedOperation);
773        }
774        let common = read.len().min(write.len());
775        self.transfer_inner(&mut read[..common], &write[..common]).await?;
776        if read.len() > common {
777            self.read(&mut read[common..]).await?;
778        }
779        if write.len() > common {
780            self.write(&write[common..]).await?;
781        }
782        Ok(())
783    }
784
785    /// Transfer using the same buffer for transmit and receive.
786    pub async fn transfer_in_place<W: Word>(&mut self, data: &mut [W]) -> Result<(), Error> {
787        if data.is_empty() {
788            return Ok(());
789        }
790        if self.miso.is_none() || self.mosi.is_none() {
791            return Err(Error::UnsupportedOperation);
792        }
793        self.transfer_inner(data, data).await
794    }
795}
796
797impl<'d, T: Instance, W: Word> embedded_hal_async::spi::SpiBus<W> for Spi<'d, T, Async> {
798    async fn write(&mut self, data: &[W]) -> Result<(), Self::Error> {
799        self.write(data).await
800    }
801
802    async fn read(&mut self, data: &mut [W]) -> Result<(), Self::Error> {
803        self.read(data).await
804    }
805
806    async fn transfer(&mut self, read: &mut [W], write: &[W]) -> Result<(), Self::Error> {
807        self.transfer(read, write).await
808    }
809
810    async fn transfer_in_place(&mut self, data: &mut [W]) -> Result<(), Self::Error> {
811        self.transfer_in_place(data).await
812    }
813
814    async fn flush(&mut self) -> Result<(), Self::Error> {
815        self.flush().await
816    }
817}
818
819impl<'d, T: Instance, M: PeriMode> Drop for Spi<'d, T, M> {
820    fn drop(&mut self) {
821        use crate::gpio::SealedPin;
822        cleanup(T::REGS);
823        #[cfg(spi_v4x7)]
824        {
825            use crate::interrupt::typelevel::Interrupt;
826            T::Interrupt::disable();
827        }
828
829        self.sck.as_ref().map(|x| x.set_as_disconnected());
830        self.mosi.as_ref().map(|x| x.set_as_disconnected());
831        self.miso.as_ref().map(|x| x.set_as_disconnected());
832
833        T::disable();
834    }
835}
836
837// Get CTRL1.BR
838#[inline]
839fn calculate_baud_rate(clock: u32, frequency: u32) -> Option<BaudRate> {
840    if clock == 0 || frequency == 0 {
841        return None;
842    }
843    for (divisor, setting) in [
844        (2u64, BaudRate::DIV_2),
845        (4, BaudRate::DIV_4),
846        (8, BaudRate::DIV_8),
847        (16, BaudRate::DIV_16),
848        (32, BaudRate::DIV_32),
849        (64, BaudRate::DIV_64),
850        (128, BaudRate::DIV_128),
851        (256, BaudRate::DIV_256),
852    ] {
853        if u64::from(clock) <= u64::from(frequency) * divisor {
854            return Some(setting);
855        }
856    }
857    None
858}
859
860fn configure_high_speed(regs: Regs, clock: u32, divisor: BaudRate, receive: bool) {
861    #[cfg(spi_v4x7)]
862    let enabled = receive && divisor == BaudRate::DIV_2;
863    #[cfg(not(spi_v4x7))]
864    let enabled = receive && divisor == BaudRate::DIV_2 && clock / 2 >= 36_000_000;
865    regs.hscr().modify(|w| {
866        w.set_hsrxen(enabled);
867        // CH32H4 and CH32V4x7 both add a second high-speed receive bit; the
868        // remaining families stop at `HSRXEN`.
869        #[cfg(any(spi_v4x7, spi_h4))]
870        w.set_hsrxen2(enabled && clock >= 120_000_000);
871    });
872}
873
874fn check_error_flags(sr: &pac::spi::regs::Statr) -> Result<(), Error> {
875    if sr.ovr() {
876        return Err(Error::Overrun);
877    }
878    if sr.modf() {
879        return Err(Error::ModeFault);
880    }
881    if sr.crcerr() {
882        return Err(Error::Crc);
883    }
884
885    Ok(())
886}
887
888fn spin_until_tx_ready(regs: &pac::spi::Spi) -> Result<(), Error> {
889    loop {
890        let sr = regs.statr().read();
891
892        check_error_flags(&sr)?;
893
894        if sr.txe() {
895            return Ok(());
896        }
897    }
898}
899
900fn spin_until_rx_ready(regs: &pac::spi::Spi) -> Result<(), Error> {
901    loop {
902        let sr = regs.statr().read();
903
904        check_error_flags(&sr)?;
905
906        if sr.rxne() {
907            return Ok(());
908        }
909    }
910}
911
912fn flush_rx_fifo(regs: pac::spi::Spi) {
913    while regs.statr().read().rxne() {
914        let _ = regs.datar().read();
915    }
916}
917
918fn cleanup(regs: Regs) {
919    regs.ctlr2().modify(|reg| {
920        reg.set_txdmaen(false);
921        reg.set_rxdmaen(false);
922        reg.set_errie(false);
923    });
924    let _ = regs.statr().read();
925    regs.ctlr1().modify(|w| w.set_spe(false));
926    flush_rx_fifo(regs);
927    let _ = regs.datar().read();
928    let _ = regs.statr().read();
929    regs.statr().write(|w| w.set_crcerr(false));
930    regs.ctlr1().modify(|w| {
931        w.set_mstr(true);
932        w.set_bidimode(false);
933        w.set_bidioe(false);
934        w.set_rxonly(false);
935    });
936}
937
938fn transfer_word<W: Word>(regs: &pac::spi::Spi, tx_word: W) -> Result<W, Error> {
939    spin_until_tx_ready(regs)?;
940
941    unsafe {
942        ptr::write_volatile(regs.datar().as_ptr() as _, tx_word);
943    }
944
945    spin_until_rx_ready(regs)?;
946
947    let rx_word = unsafe { ptr::read_volatile(regs.datar().as_ptr() as _) };
948    Ok(rx_word)
949}
950
951impl<'d, T: Instance, M: PeriMode> embedded_hal::spi::ErrorType for Spi<'d, T, M> {
952    type Error = Error;
953}
954
955impl<'d, T: Instance, W: Word, M: PeriMode> embedded_hal::spi::SpiBus<W> for Spi<'d, T, M> {
956    fn flush(&mut self) -> Result<(), Self::Error> {
957        self.blocking_flush()
958    }
959
960    fn read(&mut self, words: &mut [W]) -> Result<(), Self::Error> {
961        self.blocking_read(words)
962    }
963
964    fn write(&mut self, words: &[W]) -> Result<(), Self::Error> {
965        self.blocking_write(words)
966    }
967
968    fn transfer(&mut self, read: &mut [W], write: &[W]) -> Result<(), Self::Error> {
969        self.blocking_transfer(read, write)
970    }
971
972    fn transfer_in_place(&mut self, words: &mut [W]) -> Result<(), Self::Error> {
973        self.blocking_transfer_in_place(words)
974    }
975}
976
977impl embedded_hal::spi::Error for Error {
978    fn kind(&self) -> embedded_hal::spi::ErrorKind {
979        match *self {
980            Self::Framing => embedded_hal::spi::ErrorKind::FrameFormat,
981            Self::Crc => embedded_hal::spi::ErrorKind::Other,
982            Self::ModeFault => embedded_hal::spi::ErrorKind::ModeFault,
983            Self::Overrun => embedded_hal::spi::ErrorKind::Overrun,
984            Self::BufferTooLong | Self::UnsupportedOperation => embedded_hal::spi::ErrorKind::Other,
985        }
986    }
987}
988
989trait SealedWord {
990    const CONFIG: word_impl::Config;
991}
992
993/// Word sizes usable for SPI.
994#[allow(private_bounds)]
995pub trait Word: word::Word + SealedWord {}
996
997macro_rules! impl_word {
998    ($T:ty, $config:expr) => {
999        impl SealedWord for $T {
1000            const CONFIG: Config = $config;
1001        }
1002        impl Word for $T {}
1003    };
1004}
1005
1006mod word_impl {
1007    use super::*;
1008
1009    pub type Config = u8;
1010
1011    impl_word!(u8, 0);
1012    impl_word!(u16, 1);
1013}
1014
1015trait SealedInstance {
1016    const REGS: Regs;
1017    fn state() -> &'static State;
1018}
1019
1020struct State {
1021    waker: AtomicWaker,
1022}
1023
1024/// SPI instance trait.
1025#[allow(private_bounds)]
1026pub trait Instance:
1027    embassy_hal_internal::PeripheralType + crate::peripheral::RccPeripheral + crate::peripheral::RemapBound + SealedInstance
1028{
1029    /// SPI global interrupt.
1030    type Interrupt: interrupt::typelevel::Interrupt;
1031}
1032
1033foreach_peripheral!(
1034    (spi, $inst:ident) => {
1035        impl SealedInstance for peripherals::$inst {
1036            const REGS: Regs = crate::pac::$inst;
1037            fn state() -> &'static State {
1038                static STATE: State = State { waker: AtomicWaker::new() };
1039                &STATE
1040            }
1041        }
1042
1043        impl Instance for peripherals::$inst {
1044            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1045        }
1046    };
1047);
1048
1049pin_trait!(SckPin, Instance);
1050pin_trait!(MosiPin, Instance);
1051pin_trait!(MisoPin, Instance);
1052pin_trait!(CsPin, Instance);
1053
1054// I2S pins
1055pin_trait!(MckPin, Instance);
1056pin_trait!(CkPin, Instance);
1057
1058dma_trait!(RxDma, Instance);
1059dma_trait!(TxDma, Instance);