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