1use core::{marker::PhantomData, sync::atomic::Ordering};
38
39#[cfg(spi_master_supports_dma)]
40mod dma;
41mod low_level;
42
43#[instability::unstable]
44#[cfg(spi_master_supports_dma)]
45pub use dma::*;
46use embedded_hal::spi::SpiBus;
47use embedded_hal_async::spi::SpiBus as SpiBusAsync;
48use enumset::EnumSetType;
49use low_level::{Driver, SpiWrapper};
50pub use low_level::{Info, Instance, QspiInstance, State};
51use procmacros::doc_replace;
52
53use super::{BitOrder, Error, Mode};
54use crate::{
55 Async,
56 Blocking,
57 DriverMode,
58 gpio::{
59 InputConfig,
60 NoPin,
61 OutputConfig,
62 OutputSignal,
63 PinGuard,
64 interconnect::{self, PeripheralInput, PeripheralOutput},
65 },
66 interrupt::InterruptHandler,
67 private::Sealed,
68 spi::master::low_level::SpiClockGuard,
69 time::Rate,
70};
71
72#[derive(Debug, Hash, EnumSetType)]
74#[cfg_attr(feature = "defmt", derive(defmt::Format))]
75#[non_exhaustive]
76#[instability::unstable]
77pub enum SpiInterrupt {
78 TransferDone,
83
84 #[cfg(spi_master_has_dma_segmented_transfer)]
86 DmaSegmentedTransferDone,
87
88 #[cfg(spi_master_has_app_interrupts)]
90 App2,
91
92 #[cfg(spi_master_has_app_interrupts)]
94 App1,
95}
96
97const FIFO_SIZE: usize = property!("spi_master.fifo_size");
99
100const EMPTY_WRITE_PAD: u8 = 0x00;
102
103#[non_exhaustive]
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109#[cfg_attr(feature = "defmt", derive(defmt::Format))]
110#[instability::unstable]
111pub enum Command {
112 None,
114 _1Bit(u16, DataMode),
116 _2Bit(u16, DataMode),
118 _3Bit(u16, DataMode),
120 _4Bit(u16, DataMode),
122 _5Bit(u16, DataMode),
124 _6Bit(u16, DataMode),
126 _7Bit(u16, DataMode),
128 _8Bit(u16, DataMode),
130 _9Bit(u16, DataMode),
132 _10Bit(u16, DataMode),
134 _11Bit(u16, DataMode),
136 _12Bit(u16, DataMode),
138 _13Bit(u16, DataMode),
140 _14Bit(u16, DataMode),
142 _15Bit(u16, DataMode),
144 _16Bit(u16, DataMode),
146}
147
148impl Command {
149 fn width(&self) -> usize {
150 match self {
151 Command::None => 0,
152 Command::_1Bit(_, _) => 1,
153 Command::_2Bit(_, _) => 2,
154 Command::_3Bit(_, _) => 3,
155 Command::_4Bit(_, _) => 4,
156 Command::_5Bit(_, _) => 5,
157 Command::_6Bit(_, _) => 6,
158 Command::_7Bit(_, _) => 7,
159 Command::_8Bit(_, _) => 8,
160 Command::_9Bit(_, _) => 9,
161 Command::_10Bit(_, _) => 10,
162 Command::_11Bit(_, _) => 11,
163 Command::_12Bit(_, _) => 12,
164 Command::_13Bit(_, _) => 13,
165 Command::_14Bit(_, _) => 14,
166 Command::_15Bit(_, _) => 15,
167 Command::_16Bit(_, _) => 16,
168 }
169 }
170
171 fn value(&self) -> u16 {
172 match self {
173 Command::None => 0,
174 Command::_1Bit(value, _)
175 | Command::_2Bit(value, _)
176 | Command::_3Bit(value, _)
177 | Command::_4Bit(value, _)
178 | Command::_5Bit(value, _)
179 | Command::_6Bit(value, _)
180 | Command::_7Bit(value, _)
181 | Command::_8Bit(value, _)
182 | Command::_9Bit(value, _)
183 | Command::_10Bit(value, _)
184 | Command::_11Bit(value, _)
185 | Command::_12Bit(value, _)
186 | Command::_13Bit(value, _)
187 | Command::_14Bit(value, _)
188 | Command::_15Bit(value, _)
189 | Command::_16Bit(value, _) => *value,
190 }
191 }
192
193 fn mode(&self) -> DataMode {
194 match self {
195 Command::None => DataMode::SingleTwoDataLines,
196 Command::_1Bit(_, mode)
197 | Command::_2Bit(_, mode)
198 | Command::_3Bit(_, mode)
199 | Command::_4Bit(_, mode)
200 | Command::_5Bit(_, mode)
201 | Command::_6Bit(_, mode)
202 | Command::_7Bit(_, mode)
203 | Command::_8Bit(_, mode)
204 | Command::_9Bit(_, mode)
205 | Command::_10Bit(_, mode)
206 | Command::_11Bit(_, mode)
207 | Command::_12Bit(_, mode)
208 | Command::_13Bit(_, mode)
209 | Command::_14Bit(_, mode)
210 | Command::_15Bit(_, mode)
211 | Command::_16Bit(_, mode) => *mode,
212 }
213 }
214
215 fn is_none(&self) -> bool {
216 matches!(self, Command::None)
217 }
218}
219
220#[non_exhaustive]
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226#[cfg_attr(feature = "defmt", derive(defmt::Format))]
227#[instability::unstable]
228pub enum Address {
229 None,
231 _1Bit(u32, DataMode),
233 _2Bit(u32, DataMode),
235 _3Bit(u32, DataMode),
237 _4Bit(u32, DataMode),
239 _5Bit(u32, DataMode),
241 _6Bit(u32, DataMode),
243 _7Bit(u32, DataMode),
245 _8Bit(u32, DataMode),
247 _9Bit(u32, DataMode),
249 _10Bit(u32, DataMode),
251 _11Bit(u32, DataMode),
253 _12Bit(u32, DataMode),
255 _13Bit(u32, DataMode),
257 _14Bit(u32, DataMode),
259 _15Bit(u32, DataMode),
261 _16Bit(u32, DataMode),
263 _17Bit(u32, DataMode),
265 _18Bit(u32, DataMode),
267 _19Bit(u32, DataMode),
269 _20Bit(u32, DataMode),
271 _21Bit(u32, DataMode),
273 _22Bit(u32, DataMode),
275 _23Bit(u32, DataMode),
277 _24Bit(u32, DataMode),
279 _25Bit(u32, DataMode),
281 _26Bit(u32, DataMode),
283 _27Bit(u32, DataMode),
285 _28Bit(u32, DataMode),
287 _29Bit(u32, DataMode),
289 _30Bit(u32, DataMode),
291 _31Bit(u32, DataMode),
293 _32Bit(u32, DataMode),
295}
296
297impl Address {
298 fn width(&self) -> usize {
299 match self {
300 Address::None => 0,
301 Address::_1Bit(_, _) => 1,
302 Address::_2Bit(_, _) => 2,
303 Address::_3Bit(_, _) => 3,
304 Address::_4Bit(_, _) => 4,
305 Address::_5Bit(_, _) => 5,
306 Address::_6Bit(_, _) => 6,
307 Address::_7Bit(_, _) => 7,
308 Address::_8Bit(_, _) => 8,
309 Address::_9Bit(_, _) => 9,
310 Address::_10Bit(_, _) => 10,
311 Address::_11Bit(_, _) => 11,
312 Address::_12Bit(_, _) => 12,
313 Address::_13Bit(_, _) => 13,
314 Address::_14Bit(_, _) => 14,
315 Address::_15Bit(_, _) => 15,
316 Address::_16Bit(_, _) => 16,
317 Address::_17Bit(_, _) => 17,
318 Address::_18Bit(_, _) => 18,
319 Address::_19Bit(_, _) => 19,
320 Address::_20Bit(_, _) => 20,
321 Address::_21Bit(_, _) => 21,
322 Address::_22Bit(_, _) => 22,
323 Address::_23Bit(_, _) => 23,
324 Address::_24Bit(_, _) => 24,
325 Address::_25Bit(_, _) => 25,
326 Address::_26Bit(_, _) => 26,
327 Address::_27Bit(_, _) => 27,
328 Address::_28Bit(_, _) => 28,
329 Address::_29Bit(_, _) => 29,
330 Address::_30Bit(_, _) => 30,
331 Address::_31Bit(_, _) => 31,
332 Address::_32Bit(_, _) => 32,
333 }
334 }
335
336 fn value(&self) -> u32 {
337 match self {
338 Address::None => 0,
339 Address::_1Bit(value, _)
340 | Address::_2Bit(value, _)
341 | Address::_3Bit(value, _)
342 | Address::_4Bit(value, _)
343 | Address::_5Bit(value, _)
344 | Address::_6Bit(value, _)
345 | Address::_7Bit(value, _)
346 | Address::_8Bit(value, _)
347 | Address::_9Bit(value, _)
348 | Address::_10Bit(value, _)
349 | Address::_11Bit(value, _)
350 | Address::_12Bit(value, _)
351 | Address::_13Bit(value, _)
352 | Address::_14Bit(value, _)
353 | Address::_15Bit(value, _)
354 | Address::_16Bit(value, _)
355 | Address::_17Bit(value, _)
356 | Address::_18Bit(value, _)
357 | Address::_19Bit(value, _)
358 | Address::_20Bit(value, _)
359 | Address::_21Bit(value, _)
360 | Address::_22Bit(value, _)
361 | Address::_23Bit(value, _)
362 | Address::_24Bit(value, _)
363 | Address::_25Bit(value, _)
364 | Address::_26Bit(value, _)
365 | Address::_27Bit(value, _)
366 | Address::_28Bit(value, _)
367 | Address::_29Bit(value, _)
368 | Address::_30Bit(value, _)
369 | Address::_31Bit(value, _)
370 | Address::_32Bit(value, _) => *value,
371 }
372 }
373
374 fn is_none(&self) -> bool {
375 matches!(self, Address::None)
376 }
377
378 fn mode(&self) -> DataMode {
379 match self {
380 Address::None => DataMode::SingleTwoDataLines,
381 Address::_1Bit(_, mode)
382 | Address::_2Bit(_, mode)
383 | Address::_3Bit(_, mode)
384 | Address::_4Bit(_, mode)
385 | Address::_5Bit(_, mode)
386 | Address::_6Bit(_, mode)
387 | Address::_7Bit(_, mode)
388 | Address::_8Bit(_, mode)
389 | Address::_9Bit(_, mode)
390 | Address::_10Bit(_, mode)
391 | Address::_11Bit(_, mode)
392 | Address::_12Bit(_, mode)
393 | Address::_13Bit(_, mode)
394 | Address::_14Bit(_, mode)
395 | Address::_15Bit(_, mode)
396 | Address::_16Bit(_, mode)
397 | Address::_17Bit(_, mode)
398 | Address::_18Bit(_, mode)
399 | Address::_19Bit(_, mode)
400 | Address::_20Bit(_, mode)
401 | Address::_21Bit(_, mode)
402 | Address::_22Bit(_, mode)
403 | Address::_23Bit(_, mode)
404 | Address::_24Bit(_, mode)
405 | Address::_25Bit(_, mode)
406 | Address::_26Bit(_, mode)
407 | Address::_27Bit(_, mode)
408 | Address::_28Bit(_, mode)
409 | Address::_29Bit(_, mode)
410 | Address::_30Bit(_, mode)
411 | Address::_31Bit(_, mode)
412 | Address::_32Bit(_, mode) => *mode,
413 }
414 }
415}
416
417#[instability::unstable]
419pub use crate::soc::clocks::SpiFunctionClockConfig as ClockSource;
420
421#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, procmacros::BuilderLite)]
423#[cfg_attr(feature = "defmt", derive(defmt::Format))]
424#[non_exhaustive]
425pub struct Config {
426 #[builder_lite(skip)]
437 reg: Result<u32, ConfigError>,
438
439 #[builder_lite(skip_setter)]
441 frequency: Rate,
442
443 #[builder_lite(unstable)]
445 #[builder_lite(skip_setter)]
446 clock_source: ClockSource,
447
448 mode: Mode,
450
451 read_bit_order: BitOrder,
453
454 write_bit_order: BitOrder,
456
457 #[builder_lite(unstable)]
470 min_async_transfer_size: usize,
471}
472
473impl Default for Config {
474 fn default() -> Self {
475 let mut this = Config {
476 reg: Ok(0),
477 frequency: Rate::from_mhz(1),
478 clock_source: ClockSource::default(),
479 mode: Mode::_0,
480 read_bit_order: BitOrder::MsbFirst,
481 write_bit_order: BitOrder::MsbFirst,
482 min_async_transfer_size: 0,
483 };
484
485 this.reg = this.recalculate();
486
487 this
488 }
489}
490
491impl Config {
492 pub fn with_frequency(mut self, frequency: Rate) -> Self {
497 self.frequency = frequency;
498 self.reg = self.recalculate();
499
500 self
501 }
502
503 #[instability::unstable]
505 pub fn with_clock_source(mut self, clock_source: ClockSource) -> Self {
506 self.clock_source = clock_source;
507 self.reg = self.recalculate();
508
509 self
510 }
511
512 fn clock_source_freq_hz(&self) -> Rate {
513 Rate::from_hz(
514 crate::soc::clocks::SpiInstance::function_clock_source_frequency(self.clock_source),
515 )
516 }
517
518 fn recalculate(&self) -> Result<u32, ConfigError> {
519 let source_freq = self.clock_source_freq_hz();
522
523 if self.frequency >= source_freq {
527 return Ok(1 << 31);
530 }
531
532 let (n, pre) = Self::divider_pair(source_freq.as_hz(), self.frequency.as_hz());
533
534 let l = n;
536
537 let h = (n / 2).max(1);
539
540 Ok((l - 1) | ((h - 1) << 6) | ((n - 1) << 12) | ((pre - 1) << 18)) }
545
546 fn divider_pair(source_freq_hz: u32, target_freq_hz: u32) -> (u32, u32) {
558 if target_freq_hz == 0 {
561 return (64, 16);
562 }
563
564 let min_divider = source_freq_hz.div_ceil(target_freq_hz).max(2);
567
568 if min_divider <= 64 {
572 return (min_divider, 1);
573 }
574
575 let mut best = (64, 16);
584 let mut best_divider = 64 * 16;
585
586 let mut pre = min_divider.div_ceil(64);
590 while pre <= 16 {
591 let n = min_divider.div_ceil(pre);
594 let divider = pre * n;
595
596 if divider < best_divider {
597 best = (n, pre);
598 best_divider = divider;
599
600 if divider == min_divider {
602 break;
603 }
604 }
605
606 pre += 1;
607 }
608
609 best
610 }
611
612 fn raw_clock_reg_value(&self) -> Result<u32, ConfigError> {
613 self.reg
614 }
615
616 fn validate(&self) -> Result<(), ConfigError> {
617 let source_freq = self.clock_source_freq_hz();
618 let min_divider = 1;
619 let max_divider = 16 * 64; if self.frequency.as_hz() < source_freq.as_hz().div_ceil(max_divider)
624 || self.frequency > source_freq / min_divider
625 {
626 return Err(ConfigError::FrequencyOutOfRange);
627 }
628
629 Ok(())
630 }
631}
632
633const SIO_PIN_COUNT: usize = 4 + cfg!(spi_master_has_octal) as usize * 4;
634
635#[derive(Debug)]
636#[cfg_attr(feature = "defmt", derive(defmt::Format))]
637struct SpiPinGuard {
638 sclk_pin: PinGuard,
639 cs_pin: PinGuard,
640 sio_pins: [PinGuard; SIO_PIN_COUNT],
641}
642
643impl SpiPinGuard {
644 const fn new_unconnected() -> Self {
645 Self {
646 sclk_pin: PinGuard::new_unconnected(),
647 cs_pin: PinGuard::new_unconnected(),
648 sio_pins: [const { PinGuard::new_unconnected() }; SIO_PIN_COUNT],
649 }
650 }
651}
652
653#[non_exhaustive]
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
656#[cfg_attr(feature = "defmt", derive(defmt::Format))]
657pub enum ConfigError {
658 FrequencyOutOfRange,
660}
661
662impl core::error::Error for ConfigError {}
663
664impl core::fmt::Display for ConfigError {
665 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
666 match self {
667 ConfigError::FrequencyOutOfRange => {
668 write!(f, "The requested frequency is not in the supported range")
669 }
670 }
671 }
672}
673
674#[procmacros::doc_replace]
675#[derive(Debug)]
697#[cfg_attr(feature = "defmt", derive(defmt::Format))]
698pub struct Spi<'d, Dm: DriverMode> {
699 spi: SpiWrapper<'d>,
700 _mode: PhantomData<Dm>,
701}
702
703impl<Dm: DriverMode> Sealed for Spi<'_, Dm> {}
704
705impl<'d> Spi<'d, Blocking> {
706 #[procmacros::doc_replace]
707 pub fn new(spi: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
728 let mut this = Spi {
729 _mode: PhantomData,
730 spi: SpiWrapper::new(spi),
731 };
732
733 this.driver().init();
734 this.apply_config(&config)?;
735
736 let this = this.with_sck(NoPin).with_cs(NoPin);
737
738 for sio in 0..8 {
739 if let Some(signal) = this.driver().info.opt_sio_input(sio) {
740 signal.connect_to(&NoPin);
741 }
742 if let Some(signal) = this.driver().info.opt_sio_output(sio) {
743 signal.connect_to(&NoPin);
744 }
745 }
746
747 Ok(this)
748 }
749
750 pub fn into_async(mut self) -> Spi<'d, Async> {
755 self.set_interrupt_handler(self.spi.info().async_handler);
756 Spi {
757 spi: self.spi,
758 _mode: PhantomData,
759 }
760 }
761
762 #[doc_replace(
763 "peripheral_on" => {
764 cfg(multi_core) => "peripheral on the current core",
765 _ => "peripheral",
766 }
767 )]
768 #[instability::unstable]
780 pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
781 self.spi.set_interrupt_handler(handler);
782 }
783}
784
785#[instability::unstable]
786impl crate::interrupt::InterruptConfigurable for Spi<'_, Blocking> {
787 fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
791 self.set_interrupt_handler(handler);
792 }
793}
794
795impl<'d> Spi<'d, Async> {
796 pub fn into_blocking(self) -> Spi<'d, Blocking> {
801 self.spi.disable_peri_interrupt_on_all_cores();
802 Spi {
803 spi: self.spi,
804 _mode: PhantomData,
805 }
806 }
807
808 #[procmacros::doc_replace]
809 pub async fn flush_async(&mut self) -> Result<(), Error> {
832 Ok(())
833 }
834
835 #[procmacros::doc_replace]
836 pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
862 let _clock = SpiClockGuard::new(self.spi.info());
863
864 self.driver().setup_full_duplex()?;
865
866 if self.use_blocking_transfer(words.len()) {
867 return self.driver().transfer_in_place(words);
868 }
869
870 self.driver().transfer_in_place_async(words).await
871 }
872
873 #[instability::unstable]
888 pub async fn half_duplex_read_async(
889 &mut self,
890 data_mode: DataMode,
891 cmd: Command,
892 address: Address,
893 dummy: u8,
894 buffer: &mut [u8],
895 ) -> Result<(), Error> {
896 let _clock = SpiClockGuard::new(self.spi.info());
897
898 if self.use_blocking_transfer(buffer.len()) {
899 return self
900 .driver()
901 .half_duplex_read(data_mode, cmd, address, dummy, buffer);
902 }
903
904 self.driver()
905 .half_duplex_read_async(data_mode, cmd, address, dummy, buffer)
906 .await
907 }
908
909 #[cfg_attr(
923 esp32,
924 doc = "Dummy phase configuration is currently not supported, only value `0` is valid (see issue [#2240](https://github.com/esp-rs/esp-hal/issues/2240))."
925 )]
926 #[instability::unstable]
927 pub async fn half_duplex_write_async(
928 &mut self,
929 data_mode: DataMode,
930 cmd: Command,
931 address: Address,
932 dummy: u8,
933 buffer: &[u8],
934 ) -> Result<(), Error> {
935 let _clock = SpiClockGuard::new(self.spi.info());
936
937 if self.use_blocking_transfer(buffer.len()) {
938 return self
939 .driver()
940 .half_duplex_write(data_mode, cmd, address, dummy, buffer);
941 }
942
943 self.driver()
944 .half_duplex_write_async(data_mode, cmd, address, dummy, buffer)
945 .await
946 }
947
948 async fn read_async(&mut self, words: &mut [u8]) -> Result<(), Error> {
951 let _clock = SpiClockGuard::new(self.spi.info());
952
953 self.driver().setup_full_duplex()?;
954
955 if self.use_blocking_transfer(words.len()) {
956 return self.driver().read(words);
957 }
958
959 self.driver().read_async(words).await
960 }
961
962 async fn write_async(&mut self, words: &[u8]) -> Result<(), Error> {
963 let _clock = SpiClockGuard::new(self.spi.info());
964
965 self.driver().setup_full_duplex()?;
966
967 if self.use_blocking_transfer(words.len()) {
968 return self.driver().write(words);
969 }
970
971 self.driver().write_async(words).await
972 }
973}
974
975macro_rules! def_with_sio_pin {
976 ($fn:ident, $n:literal) => {
977 #[doc = concat!(" Assign the SIO", stringify!($n), " pin for the SPI instance.")]
978 #[doc = " "]
979 #[doc = " Enables both input and output functionality for the pin, and connects it"]
980 #[doc = concat!(" to the SIO", stringify!($n), " output and input signals.")]
981 #[instability::unstable]
982 pub fn $fn(mut self, sio: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
983 self.spi.pins().sio_pins[$n] = self.connect_sio_pin(sio.into(), $n);
984
985 self
986 }
987 };
988}
989
990impl<'d, Dm> Spi<'d, Dm>
991where
992 Dm: DriverMode,
993{
994 fn connect_sio_pin(&self, pin: interconnect::OutputSignal<'d>, n: usize) -> PinGuard {
995 let in_signal = self.spi.info().sio_input(n);
996 let out_signal = self.spi.info().sio_output(n);
997
998 pin.apply_input_config(&InputConfig::default());
999 pin.apply_output_config(&OutputConfig::default());
1000
1001 pin.set_input_enable(true);
1002 pin.set_output_enable(false);
1003
1004 in_signal.connect_to(&pin);
1005 pin.connect_with_guard(out_signal)
1006 }
1007
1008 fn connect_sio_output_pin(&self, pin: interconnect::OutputSignal<'d>, n: usize) -> PinGuard {
1009 let out_signal = self.spi.info().sio_output(n);
1010
1011 self.connect_output_pin(pin, out_signal)
1012 }
1013
1014 fn connect_output_pin(
1015 &self,
1016 pin: interconnect::OutputSignal<'d>,
1017 signal: OutputSignal,
1018 ) -> PinGuard {
1019 pin.apply_output_config(&OutputConfig::default());
1020 pin.set_output_enable(true); pin.connect_with_guard(signal)
1023 }
1024
1025 #[procmacros::doc_replace]
1026 pub fn with_sck(mut self, sclk: impl PeripheralOutput<'d>) -> Self {
1046 let info = self.spi.info();
1047 self.spi.pins().sclk_pin = self.connect_output_pin(sclk.into(), info.sclk);
1048
1049 self
1050 }
1051
1052 #[procmacros::doc_replace]
1053 pub fn with_mosi(mut self, mosi: impl PeripheralOutput<'d>) -> Self {
1075 self.spi.pins().sio_pins[0] = self.connect_sio_output_pin(mosi.into(), 0);
1076 self
1077 }
1078
1079 #[procmacros::doc_replace]
1080 pub fn with_miso(self, miso: impl PeripheralInput<'d>) -> Self {
1101 let miso = miso.into();
1102
1103 miso.apply_input_config(&InputConfig::default());
1104 miso.set_input_enable(true);
1105
1106 self.driver().info.sio_input(1).connect_to(&miso);
1107
1108 self
1109 }
1110
1111 #[instability::unstable]
1124 pub fn with_sio0(mut self, mosi: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
1125 self.spi.pins().sio_pins[0] = self.connect_sio_pin(mosi.into(), 0);
1126
1127 self
1128 }
1129
1130 #[instability::unstable]
1142 pub fn with_sio1(mut self, sio1: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self {
1143 self.spi.pins().sio_pins[1] = self.connect_sio_pin(sio1.into(), 1);
1144
1145 self
1146 }
1147
1148 def_with_sio_pin!(with_sio2, 2);
1149 def_with_sio_pin!(with_sio3, 3);
1150
1151 #[cfg(spi_master_has_octal)]
1152 def_with_sio_pin!(with_sio4, 4);
1153
1154 #[cfg(spi_master_has_octal)]
1155 def_with_sio_pin!(with_sio5, 5);
1156
1157 #[cfg(spi_master_has_octal)]
1158 def_with_sio_pin!(with_sio6, 6);
1159
1160 #[cfg(spi_master_has_octal)]
1161 def_with_sio_pin!(with_sio7, 7);
1162
1163 #[instability::unstable]
1175 pub fn with_cs(mut self, cs: impl PeripheralOutput<'d>) -> Self {
1176 let info = self.spi.info();
1177 self.spi.pins().cs_pin = self.connect_output_pin(cs.into(), info.cs(0));
1178
1179 self
1180 }
1181
1182 #[doc_replace(
1183 "max_frequency" => {
1184 cfg(esp32h2) => "48MHz",
1185 _ => "80MHz",
1186 }
1187 )]
1188 pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
1210 self.driver().apply_config(config)
1211 }
1212
1213 #[procmacros::doc_replace]
1214 pub fn write(&mut self, words: &[u8]) -> Result<(), Error> {
1237 let _clock = SpiClockGuard::new(self.spi.info());
1238
1239 self.driver().setup_full_duplex()?;
1240 self.driver().write(words)
1241 }
1242
1243 #[procmacros::doc_replace]
1244 pub fn read(&mut self, words: &mut [u8]) -> Result<(), Error> {
1267 let _clock = SpiClockGuard::new(self.spi.info());
1268 self.driver().setup_full_duplex()?;
1269 self.driver().read(words)
1270 }
1271
1272 #[procmacros::doc_replace]
1273 pub fn transfer(&mut self, words: &mut [u8]) -> Result<(), Error> {
1296 let _clock = SpiClockGuard::new(self.spi.info());
1297 self.driver().setup_full_duplex()?;
1298 self.driver().transfer_in_place(words)
1299 }
1300
1301 #[instability::unstable]
1312 pub fn half_duplex_read(
1313 &mut self,
1314 data_mode: DataMode,
1315 cmd: Command,
1316 address: Address,
1317 dummy: u8,
1318 buffer: &mut [u8],
1319 ) -> Result<(), Error> {
1320 let _clock = SpiClockGuard::new(self.spi.info());
1321 self.driver()
1322 .half_duplex_read(data_mode, cmd, address, dummy, buffer)
1323 }
1324
1325 #[cfg_attr(
1335 esp32,
1336 doc = "Dummy phase configuration is currently not supported, only value `0` is valid (see issue [#2240](https://github.com/esp-rs/esp-hal/issues/2240))."
1337 )]
1338 #[instability::unstable]
1339 pub fn half_duplex_write(
1340 &mut self,
1341 data_mode: DataMode,
1342 cmd: Command,
1343 address: Address,
1344 dummy: u8,
1345 buffer: &[u8],
1346 ) -> Result<(), Error> {
1347 let _clock = SpiClockGuard::new(self.spi.info());
1348 self.driver()
1349 .half_duplex_write(data_mode, cmd, address, dummy, buffer)
1350 }
1351
1352 fn use_blocking_transfer(&self, transfer_size: usize) -> bool {
1353 let threshold = self
1354 .spi
1355 .state()
1356 .min_async_transfer_size
1357 .load(Ordering::Relaxed);
1358 threshold > 0 && transfer_size < threshold
1359 }
1360
1361 fn driver(&self) -> Driver {
1362 Driver {
1363 info: self.spi.info(),
1364 state: self.spi.state(),
1365 }
1366 }
1367}
1368
1369#[instability::unstable]
1370impl<Dm> embassy_embedded_hal::SetConfig for Spi<'_, Dm>
1371where
1372 Dm: DriverMode,
1373{
1374 type Config = Config;
1375 type ConfigError = ConfigError;
1376
1377 fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
1378 self.apply_config(config)
1379 }
1380}
1381
1382impl<Dm> embedded_hal::spi::ErrorType for Spi<'_, Dm>
1383where
1384 Dm: DriverMode,
1385{
1386 type Error = Error;
1387}
1388
1389impl<Dm> SpiBus for Spi<'_, Dm>
1390where
1391 Dm: DriverMode,
1392{
1393 fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
1394 self.read(words)
1395 }
1396
1397 fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
1398 self.write(words)
1399 }
1400
1401 fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
1402 let _clock = SpiClockGuard::new(self.spi.info());
1403 self.driver().setup_full_duplex()?;
1404
1405 if read.is_empty() {
1406 self.driver().write(write)
1407 } else if write.is_empty() {
1408 self.driver().read(read)
1409 } else {
1410 self.driver().transfer(read, write)
1411 }
1412 }
1413
1414 fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
1415 let _clock = SpiClockGuard::new(self.spi.info());
1416 self.driver().setup_full_duplex()?;
1417 self.driver().transfer_in_place(words)
1418 }
1419
1420 fn flush(&mut self) -> Result<(), Self::Error> {
1421 Ok(())
1422 }
1423}
1424
1425impl SpiBusAsync for Spi<'_, Async> {
1426 async fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
1427 self.read_async(words).await
1428 }
1429
1430 async fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
1431 self.write_async(words).await
1432 }
1433
1434 async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
1435 let _clock = SpiClockGuard::new(self.spi.info());
1436
1437 self.driver().setup_full_duplex()?;
1438
1439 if self.use_blocking_transfer(read.len().max(write.len())) {
1440 return if read.is_empty() {
1441 self.driver().write(write)
1442 } else if write.is_empty() {
1443 self.driver().read(read)
1444 } else {
1445 self.driver().transfer(read, write)
1446 };
1447 }
1448
1449 if read.is_empty() {
1450 self.driver().write_async(write).await
1451 } else if write.is_empty() {
1452 self.driver().read_async(read).await
1453 } else {
1454 self.driver().transfer_async(read, write).await
1455 }
1456 }
1457
1458 async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
1459 self.transfer_in_place_async(words).await
1460 }
1461
1462 async fn flush(&mut self) -> Result<(), Self::Error> {
1463 Ok(())
1464 }
1465}
1466
1467#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1469#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1470#[instability::unstable]
1471pub enum DataMode {
1472 SingleTwoDataLines,
1474 Single,
1476 Dual,
1478 Quad,
1480 #[cfg(spi_master_has_octal)]
1481 Octal,
1483}
1484
1485crate::any_peripheral! {
1486 pub peripheral AnySpi<'d> {
1488 #[cfg(spi_master_spi2)]
1489 Spi2(crate::peripherals::SPI2<'d>),
1490 #[cfg(spi_master_spi3)]
1491 Spi3(crate::peripherals::SPI3<'d>),
1492 }
1493}
1494
1495#[cfg(spi_master_supports_dma)]
1496with_spi_master_dma_engine! {
1497 ($engine:tt, $any_ch:ident) => {
1498 use crate::dma::DmaEligiblePeripheral;
1499
1500 impl<'d> DmaEligiblePeripheral<crate::dma::$any_ch<'d>> for AnySpi<'d> {
1501 fn dma_peripheral(&self) -> crate::dma::DmaPeripheral {
1502 any::delegate!(self, spi => { spi.dma_peripheral() })
1503 }
1504 }
1505 };
1506}
1507
1508impl QspiInstance for AnySpi<'_> {}
1509
1510impl Instance for AnySpi<'_> {
1511 #[inline]
1512 fn parts(&self) -> (&'static Info, &'static State) {
1513 any::delegate!(self, spi => { spi.parts() })
1514 }
1515}
1516
1517impl AnySpi<'_> {
1518 fn bind_peri_interrupt(&self, handler: InterruptHandler) {
1519 any::delegate!(self, spi => { spi.bind_peri_interrupt(handler) })
1520 }
1521
1522 fn disable_peri_interrupt_on_all_cores(&self) {
1523 any::delegate!(self, spi => { spi.disable_peri_interrupt_on_all_cores() })
1524 }
1525
1526 fn set_interrupt_handler(&self, handler: InterruptHandler) {
1527 self.disable_peri_interrupt_on_all_cores();
1528 self.bind_peri_interrupt(handler);
1529 }
1530}