spi.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*!
  2. # Serial Peripheral Interface
  3. To construct the SPI instances, use the `Spi::spiX` functions.
  4. The pin parameter is a tuple containing `(sck, miso, mosi)` which should be configured as `(Alternate<PushPull>, Input<Floating>, Alternate<PushPull>)`.
  5. You can also use `NoSck`, `NoMiso` or `NoMosi` if you don't want to use the pins
  6. - `SPI1` can use `(PA5, PA6, PA7)` or `(PB3, PB4, PB5)`.
  7. - `SPI2` can use `(PB13, PB14, PB15)`
  8. - `SPI3` can use `(PB3, PB4, PB5)` or `(PC10, PC11, PC12)`
  9. ## Initialisation example
  10. ```rust
  11. // Acquire the GPIOB peripheral
  12. let mut gpiob = dp.GPIOB.split(&mut rcc.apb2);
  13. let pins = (
  14. gpiob.pb13.into_alternate_push_pull(&mut gpiob.crh),
  15. gpiob.pb14.into_floating_input(&mut gpiob.crh),
  16. gpiob.pb15.into_alternate_push_pull(&mut gpiob.crh),
  17. );
  18. let spi_mode = Mode {
  19. polarity: Polarity::IdleLow,
  20. phase: Phase::CaptureOnFirstTransition,
  21. };
  22. let spi = Spi::spi2(dp.SPI2, pins, spi_mode, 100.khz(), clocks, &mut rcc.apb1);
  23. ```
  24. */
  25. use core::ops::Deref;
  26. use core::ptr;
  27. pub use crate::hal::spi::{FullDuplex, Mode, Phase, Polarity};
  28. #[cfg(any(feature = "high", feature = "connectivity"))]
  29. use crate::pac::SPI3;
  30. use crate::pac::{SPI1, SPI2};
  31. use crate::afio::MAPR;
  32. use crate::dma::dma1::{C3, C5};
  33. #[cfg(feature = "connectivity")]
  34. use crate::dma::dma2::C2;
  35. use crate::dma::{Static, Transfer, TransferPayload, Transmit, TxDma, R};
  36. use crate::gpio::gpioa::{PA5, PA6, PA7};
  37. use crate::gpio::gpiob::{PB13, PB14, PB15, PB3, PB4, PB5};
  38. #[cfg(feature = "connectivity")]
  39. use crate::gpio::gpioc::{PC10, PC11, PC12};
  40. use crate::gpio::{Alternate, Floating, Input, PushPull};
  41. use crate::rcc::{Clocks, Enable, GetBusFreq, Reset, APB1, APB2};
  42. use crate::time::Hertz;
  43. use core::sync::atomic::{self, Ordering};
  44. use as_slice::AsSlice;
  45. /// SPI error
  46. #[derive(Debug)]
  47. pub enum Error {
  48. /// Overrun occurred
  49. Overrun,
  50. /// Mode fault occurred
  51. ModeFault,
  52. /// CRC error
  53. Crc,
  54. #[doc(hidden)]
  55. _Extensible,
  56. }
  57. use core::marker::PhantomData;
  58. mod sealed {
  59. pub trait Remap {
  60. type Periph;
  61. const REMAP: bool;
  62. }
  63. pub trait Sck<REMAP> {}
  64. pub trait Miso<REMAP> {}
  65. pub trait Mosi<REMAP> {}
  66. pub struct _Sck;
  67. pub struct _Miso;
  68. pub struct _Mosi;
  69. }
  70. use sealed::{Miso, Mosi, Remap, Sck};
  71. pub trait Pins<REMAP, P> {
  72. type _Pos;
  73. }
  74. macro_rules! pins_impl {
  75. ( $( ( $($PINX:ident),+ ), ( $($TRAIT:ident),+ ), ( $($POS:ident),* ); )+ ) => {
  76. $(
  77. #[allow(unused_parens)]
  78. impl<REMAP, $($PINX,)+> Pins<REMAP, ($(sealed::$POS),+)> for ($($PINX),+)
  79. where
  80. $($PINX: $TRAIT<REMAP>,)+
  81. {
  82. type _Pos = ($(sealed::$POS),+);
  83. }
  84. )+
  85. };
  86. }
  87. pins_impl!(
  88. (SCK, MISO, MOSI), (Sck, Miso, Mosi), (_Sck, _Miso, _Mosi);
  89. (SCK, MOSI, MISO), (Sck, Mosi, Miso), (_Sck, _Mosi, _Miso);
  90. (MOSI, SCK, MISO), (Mosi, Sck, Miso), (_Mosi, _Sck, _Miso);
  91. (MOSI, MISO, SCK), (Mosi, Miso, Sck), (_Mosi, _Miso, _Sck);
  92. (MISO, MOSI, SCK), (Miso, Mosi, Sck), (_Miso, _Mosi, _Sck);
  93. (MISO, SCK, MOSI), (Miso, Sck, Mosi), (_Miso, _Sck, _Mosi);
  94. );
  95. pub struct Spi<SPI, REMAP, PINS, FRAMESIZE> {
  96. spi: SPI,
  97. pins: PINS,
  98. _remap: PhantomData<REMAP>,
  99. _framesize: PhantomData<FRAMESIZE>,
  100. }
  101. /// A filler type for when the SCK pin is unnecessary
  102. pub struct NoSck;
  103. /// A filler type for when the Miso pin is unnecessary
  104. pub struct NoMiso;
  105. /// A filler type for when the Mosi pin is unnecessary
  106. pub struct NoMosi;
  107. impl<REMAP> Sck<REMAP> for NoSck {}
  108. impl<REMAP> Miso<REMAP> for NoMiso {}
  109. impl<REMAP> Mosi<REMAP> for NoMosi {}
  110. macro_rules! remap {
  111. ($name:ident, $SPIX:ident, $state:literal, $SCK:ident, $MISO:ident, $MOSI:ident) => {
  112. pub struct $name;
  113. impl Remap for $name {
  114. type Periph = $SPIX;
  115. const REMAP: bool = $state;
  116. }
  117. impl Sck<$name> for $SCK<Alternate<PushPull>> {}
  118. impl Miso<$name> for $MISO<Input<Floating>> {}
  119. impl Mosi<$name> for $MOSI<Alternate<PushPull>> {}
  120. };
  121. }
  122. remap!(Spi1NoRemap, SPI1, false, PA5, PA6, PA7);
  123. remap!(Spi1Remap, SPI1, true, PB3, PB4, PB5);
  124. remap!(Spi2NoRemap, SPI2, false, PB13, PB14, PB15);
  125. #[cfg(feature = "high")]
  126. remap!(Spi3NoRemap, SPI3, false, PB3, PB4, PB5);
  127. #[cfg(feature = "connectivity")]
  128. remap!(Spi3Remap, SPI3, true, PC10, PC11, PC12);
  129. impl<REMAP, PINS> Spi<SPI1, REMAP, PINS, u8> {
  130. /**
  131. Constructs an SPI instance using SPI1 in 8bit dataframe mode.
  132. The pin parameter tuple (sck, miso, mosi) should be `(PA5, PA6, PA7)` or `(PB3, PB4, PB5)` configured as `(Alternate<PushPull>, Input<Floating>, Alternate<PushPull>)`.
  133. You can also use `NoSck`, `NoMiso` or `NoMosi` if you don't want to use the pins
  134. */
  135. pub fn spi1<F, POS>(
  136. spi: SPI1,
  137. pins: PINS,
  138. mapr: &mut MAPR,
  139. mode: Mode,
  140. freq: F,
  141. clocks: Clocks,
  142. apb: &mut APB2,
  143. ) -> Self
  144. where
  145. F: Into<Hertz>,
  146. REMAP: Remap<Periph = SPI1>,
  147. PINS: Pins<REMAP, POS>,
  148. {
  149. mapr.modify_mapr(|_, w| w.spi1_remap().bit(REMAP::REMAP));
  150. Spi::<SPI1, _, _, u8>::_spi(spi, pins, mode, freq.into(), clocks, apb)
  151. }
  152. }
  153. impl<REMAP, PINS> Spi<SPI2, REMAP, PINS, u8> {
  154. /**
  155. Constructs an SPI instance using SPI2 in 8bit dataframe mode.
  156. The pin parameter tuple (sck, miso, mosi) should be `(PB13, PB14, PB15)` configured as `(Alternate<PushPull>, Input<Floating>, Alternate<PushPull>)`.
  157. You can also use `NoSck`, `NoMiso` or `NoMosi` if you don't want to use the pins
  158. */
  159. pub fn spi2<F, POS>(
  160. spi: SPI2,
  161. pins: PINS,
  162. mode: Mode,
  163. freq: F,
  164. clocks: Clocks,
  165. apb: &mut APB1,
  166. ) -> Self
  167. where
  168. F: Into<Hertz>,
  169. REMAP: Remap<Periph = SPI2>,
  170. PINS: Pins<REMAP, POS>,
  171. {
  172. Spi::<SPI2, _, _, u8>::_spi(spi, pins, mode, freq.into(), clocks, apb)
  173. }
  174. }
  175. #[cfg(any(feature = "high", feature = "connectivity"))]
  176. impl<REMAP, PINS> Spi<SPI3, REMAP, PINS, u8> {
  177. /**
  178. Constructs an SPI instance using SPI3 in 8bit dataframe mode.
  179. The pin parameter tuple (sck, miso, mosi) should be `(PB3, PB4, PB5)` or `(PC10, PC11, PC12)` configured as `(Alternate<PushPull>, Input<Floating>, Alternate<PushPull>)`.
  180. You can also use `NoSck`, `NoMiso` or `NoMosi` if you don't want to use the pins
  181. */
  182. pub fn spi3<F, POS>(
  183. spi: SPI3,
  184. pins: PINS,
  185. mode: Mode,
  186. freq: F,
  187. clocks: Clocks,
  188. apb: &mut APB1,
  189. ) -> Self
  190. where
  191. F: Into<Hertz>,
  192. REMAP: Remap<Periph = SPI3>,
  193. PINS: Pins<REMAP, POS>,
  194. {
  195. Spi::<SPI3, _, _, u8>::_spi(spi, pins, mode, freq.into(), clocks, apb)
  196. }
  197. }
  198. pub type SpiRegisterBlock = crate::pac::spi1::RegisterBlock;
  199. pub trait SpiReadWrite<T> {
  200. fn read_data_reg(&mut self) -> T;
  201. fn write_data_reg(&mut self, data: T);
  202. fn spi_write(&mut self, words: &[T]) -> Result<(), Error>;
  203. }
  204. impl<SPI, REMAP, PINS, FrameSize> SpiReadWrite<FrameSize> for Spi<SPI, REMAP, PINS, FrameSize>
  205. where
  206. SPI: Deref<Target = SpiRegisterBlock>,
  207. FrameSize: Copy,
  208. {
  209. fn read_data_reg(&mut self) -> FrameSize {
  210. // NOTE(read_volatile) read only 1 byte (the svd2rust API only allows
  211. // reading a half-word)
  212. return unsafe { ptr::read_volatile(&self.spi.dr as *const _ as *const FrameSize) };
  213. }
  214. fn write_data_reg(&mut self, data: FrameSize) {
  215. // NOTE(write_volatile) see note above
  216. unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut FrameSize, data) }
  217. }
  218. // Implement write as per the "Transmit only procedure" page 712
  219. // of RM0008 Rev 20. This is more than twice as fast as the
  220. // default Write<> implementation (which reads and drops each
  221. // received value)
  222. fn spi_write(&mut self, words: &[FrameSize]) -> Result<(), Error> {
  223. // Write each word when the tx buffer is empty
  224. for word in words {
  225. loop {
  226. let sr = self.spi.sr.read();
  227. if sr.txe().bit_is_set() {
  228. // NOTE(write_volatile) see note above
  229. // unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut u8, *word) }
  230. self.write_data_reg(*word);
  231. if sr.modf().bit_is_set() {
  232. return Err(Error::ModeFault);
  233. }
  234. break;
  235. }
  236. }
  237. }
  238. // Wait for final TXE
  239. loop {
  240. let sr = self.spi.sr.read();
  241. if sr.txe().bit_is_set() {
  242. break;
  243. }
  244. }
  245. // Wait for final !BSY
  246. loop {
  247. let sr = self.spi.sr.read();
  248. if !sr.bsy().bit_is_set() {
  249. break;
  250. }
  251. }
  252. // Clear OVR set due to dropped received values
  253. // NOTE(read_volatile) see note above
  254. // unsafe {
  255. // let _ = ptr::read_volatile(&self.spi.dr as *const _ as *const u8);
  256. // }
  257. let _ = self.read_data_reg();
  258. let _ = self.spi.sr.read();
  259. Ok(())
  260. }
  261. }
  262. impl<SPI, REMAP, PINS, FrameSize> Spi<SPI, REMAP, PINS, FrameSize>
  263. where
  264. SPI: Deref<Target = SpiRegisterBlock>,
  265. FrameSize: Copy,
  266. {
  267. #[deprecated(since = "0.6.0", note = "Please use release instead")]
  268. pub fn free(self) -> (SPI, PINS) {
  269. self.release()
  270. }
  271. pub fn release(self) -> (SPI, PINS) {
  272. (self.spi, self.pins)
  273. }
  274. }
  275. impl<SPI, REMAP, PINS> Spi<SPI, REMAP, PINS, u8>
  276. where
  277. SPI: Deref<Target = SpiRegisterBlock> + Enable + Reset,
  278. SPI::Bus: GetBusFreq,
  279. {
  280. fn _spi(
  281. spi: SPI,
  282. pins: PINS,
  283. mode: Mode,
  284. freq: Hertz,
  285. clocks: Clocks,
  286. apb: &mut SPI::Bus,
  287. ) -> Self {
  288. // enable or reset SPI
  289. SPI::enable(apb);
  290. SPI::reset(apb);
  291. // disable SS output
  292. spi.cr2.write(|w| w.ssoe().clear_bit());
  293. let br = match SPI::Bus::get_frequency(&clocks).0 / freq.0 {
  294. 0 => unreachable!(),
  295. 1..=2 => 0b000,
  296. 3..=5 => 0b001,
  297. 6..=11 => 0b010,
  298. 12..=23 => 0b011,
  299. 24..=47 => 0b100,
  300. 48..=95 => 0b101,
  301. 96..=191 => 0b110,
  302. _ => 0b111,
  303. };
  304. spi.cr1.write(|w| {
  305. w
  306. // clock phase from config
  307. .cpha()
  308. .bit(mode.phase == Phase::CaptureOnSecondTransition)
  309. // clock polarity from config
  310. .cpol()
  311. .bit(mode.polarity == Polarity::IdleHigh)
  312. // mstr: master configuration
  313. .mstr()
  314. .set_bit()
  315. // baudrate value
  316. .br()
  317. .bits(br)
  318. // lsbfirst: MSB first
  319. .lsbfirst()
  320. .clear_bit()
  321. // ssm: enable software slave management (NSS pin free for other uses)
  322. .ssm()
  323. .set_bit()
  324. // ssi: set nss high = master mode
  325. .ssi()
  326. .set_bit()
  327. // dff: 8 bit frames
  328. .dff()
  329. .clear_bit()
  330. // bidimode: 2-line unidirectional
  331. .bidimode()
  332. .clear_bit()
  333. // both TX and RX are used
  334. .rxonly()
  335. .clear_bit()
  336. // spe: enable the SPI bus
  337. .spe()
  338. .set_bit()
  339. });
  340. Spi {
  341. spi,
  342. pins,
  343. _remap: PhantomData,
  344. _framesize: PhantomData,
  345. }
  346. }
  347. /// Converts from 8bit dataframe to 16bit.
  348. pub fn frame_size_16bit(self) -> Spi<SPI, REMAP, PINS, u16> {
  349. self.spi.cr1.modify(|_, w| w.spe().clear_bit());
  350. self.spi.cr1.modify(|_, w| w.dff().set_bit());
  351. self.spi.cr1.modify(|_, w| w.spe().set_bit());
  352. Spi {
  353. spi: self.spi,
  354. pins: self.pins,
  355. _remap: PhantomData,
  356. _framesize: PhantomData,
  357. }
  358. }
  359. }
  360. impl<SPI, REMAP, PINS> Spi<SPI, REMAP, PINS, u16>
  361. where
  362. SPI: Deref<Target = SpiRegisterBlock>,
  363. {
  364. /// Converts from 16bit dataframe to 8bit.
  365. pub fn frame_size_8bit(self) -> Spi<SPI, REMAP, PINS, u8> {
  366. self.spi.cr1.modify(|_, w| w.spe().clear_bit());
  367. self.spi.cr1.modify(|_, w| w.dff().clear_bit());
  368. self.spi.cr1.modify(|_, w| w.spe().set_bit());
  369. Spi {
  370. spi: self.spi,
  371. pins: self.pins,
  372. _remap: PhantomData,
  373. _framesize: PhantomData,
  374. }
  375. }
  376. }
  377. impl<SPI, REMAP, PINS, FrameSize> crate::hal::spi::FullDuplex<FrameSize>
  378. for Spi<SPI, REMAP, PINS, FrameSize>
  379. where
  380. SPI: Deref<Target = SpiRegisterBlock>,
  381. FrameSize: Copy,
  382. {
  383. type Error = Error;
  384. fn read(&mut self) -> nb::Result<FrameSize, Error> {
  385. let sr = self.spi.sr.read();
  386. Err(if sr.ovr().bit_is_set() {
  387. nb::Error::Other(Error::Overrun)
  388. } else if sr.modf().bit_is_set() {
  389. nb::Error::Other(Error::ModeFault)
  390. } else if sr.crcerr().bit_is_set() {
  391. nb::Error::Other(Error::Crc)
  392. } else if sr.rxne().bit_is_set() {
  393. // NOTE(read_volatile) read only 1 byte (the svd2rust API only allows
  394. // reading a half-word)
  395. return Ok(self.read_data_reg());
  396. } else {
  397. nb::Error::WouldBlock
  398. })
  399. }
  400. fn send(&mut self, data: FrameSize) -> nb::Result<(), Error> {
  401. let sr = self.spi.sr.read();
  402. Err(if sr.ovr().bit_is_set() {
  403. nb::Error::Other(Error::Overrun)
  404. } else if sr.modf().bit_is_set() {
  405. nb::Error::Other(Error::ModeFault)
  406. } else if sr.crcerr().bit_is_set() {
  407. nb::Error::Other(Error::Crc)
  408. } else if sr.txe().bit_is_set() {
  409. // NOTE(write_volatile) see note above
  410. self.write_data_reg(data);
  411. return Ok(());
  412. } else {
  413. nb::Error::WouldBlock
  414. })
  415. }
  416. }
  417. impl<SPI, REMAP, PINS, FrameSize> crate::hal::blocking::spi::transfer::Default<FrameSize>
  418. for Spi<SPI, REMAP, PINS, FrameSize>
  419. where
  420. SPI: Deref<Target = SpiRegisterBlock>,
  421. FrameSize: Copy,
  422. {
  423. }
  424. impl<SPI, REMAP, PINS> crate::hal::blocking::spi::Write<u8> for Spi<SPI, REMAP, PINS, u8>
  425. where
  426. SPI: Deref<Target = SpiRegisterBlock>,
  427. {
  428. type Error = Error;
  429. // Implement write as per the "Transmit only procedure" page 712
  430. // of RM0008 Rev 20. This is more than twice as fast as the
  431. // default Write<> implementation (which reads and drops each
  432. // received value)
  433. fn write(&mut self, words: &[u8]) -> Result<(), Error> {
  434. self.spi_write(words)
  435. }
  436. }
  437. impl<SPI, REMAP, PINS> crate::hal::blocking::spi::Write<u16> for Spi<SPI, REMAP, PINS, u16>
  438. where
  439. SPI: Deref<Target = SpiRegisterBlock>,
  440. {
  441. type Error = Error;
  442. fn write(&mut self, words: &[u16]) -> Result<(), Error> {
  443. self.spi_write(words)
  444. }
  445. }
  446. // DMA
  447. pub struct SpiPayload<SPI, REMAP, PINS> {
  448. spi: Spi<SPI, REMAP, PINS, u8>,
  449. }
  450. pub type SpiTxDma<SPI, REMAP, PINS, CHANNEL> = TxDma<SpiPayload<SPI, REMAP, PINS>, CHANNEL>;
  451. macro_rules! spi_dma {
  452. ($SPIi:ident, $TCi:ident) => {
  453. impl<REMAP, PINS> Transmit for SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  454. type TxChannel = $TCi;
  455. type ReceivedWord = u8;
  456. }
  457. impl<REMAP, PINS> Spi<$SPIi, REMAP, PINS, u8> {
  458. pub fn with_tx_dma(self, channel: $TCi) -> SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  459. let payload = SpiPayload { spi: self };
  460. SpiTxDma { payload, channel }
  461. }
  462. }
  463. impl<REMAP, PINS> TransferPayload for SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  464. fn start(&mut self) {
  465. self.payload
  466. .spi
  467. .spi
  468. .cr2
  469. .modify(|_, w| w.txdmaen().set_bit());
  470. self.channel.start();
  471. }
  472. fn stop(&mut self) {
  473. self.payload
  474. .spi
  475. .spi
  476. .cr2
  477. .modify(|_, w| w.txdmaen().clear_bit());
  478. self.channel.stop();
  479. }
  480. }
  481. impl<A, B, REMAP, PIN> crate::dma::WriteDma<A, B, u8> for SpiTxDma<$SPIi, REMAP, PIN, $TCi>
  482. where
  483. A: AsSlice<Element = u8>,
  484. B: Static<A>,
  485. {
  486. fn write(mut self, buffer: B) -> Transfer<R, B, Self> {
  487. {
  488. let buffer = buffer.borrow().as_slice();
  489. self.channel.set_peripheral_address(
  490. unsafe { &(*$SPIi::ptr()).dr as *const _ as u32 },
  491. false,
  492. );
  493. self.channel
  494. .set_memory_address(buffer.as_ptr() as u32, true);
  495. self.channel.set_transfer_length(buffer.len());
  496. }
  497. atomic::compiler_fence(Ordering::Release);
  498. self.channel.ch().cr.modify(|_, w| {
  499. w
  500. // memory to memory mode disabled
  501. .mem2mem()
  502. .clear_bit()
  503. // medium channel priority level
  504. .pl()
  505. .medium()
  506. // 8-bit memory size
  507. .msize()
  508. .bits8()
  509. // 8-bit peripheral size
  510. .psize()
  511. .bits8()
  512. // circular mode disabled
  513. .circ()
  514. .clear_bit()
  515. // read from memory
  516. .dir()
  517. .set_bit()
  518. });
  519. self.start();
  520. Transfer::r(buffer, self)
  521. }
  522. }
  523. };
  524. }
  525. spi_dma!(SPI1, C3);
  526. spi_dma!(SPI2, C5);
  527. #[cfg(feature = "connectivity")]
  528. spi_dma!(SPI3, C2);