spi.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. mapr: &mut MAPR,
  186. mode: Mode,
  187. freq: F,
  188. clocks: Clocks,
  189. apb: &mut APB1,
  190. ) -> Self
  191. where
  192. F: Into<Hertz>,
  193. REMAP: Remap<Periph = SPI3>,
  194. PINS: Pins<REMAP, POS>,
  195. {
  196. mapr.modify_mapr(|_, w| w.spi3_remap().bit(REMAP::REMAP));
  197. Spi::<SPI3, _, _, u8>::_spi(spi, pins, mode, freq.into(), clocks, apb)
  198. }
  199. }
  200. pub type SpiRegisterBlock = crate::pac::spi1::RegisterBlock;
  201. pub trait SpiReadWrite<T> {
  202. fn read_data_reg(&mut self) -> T;
  203. fn write_data_reg(&mut self, data: T);
  204. fn spi_write(&mut self, words: &[T]) -> Result<(), Error>;
  205. }
  206. impl<SPI, REMAP, PINS, FrameSize> SpiReadWrite<FrameSize> for Spi<SPI, REMAP, PINS, FrameSize>
  207. where
  208. SPI: Deref<Target = SpiRegisterBlock>,
  209. FrameSize: Copy,
  210. {
  211. fn read_data_reg(&mut self) -> FrameSize {
  212. // NOTE(read_volatile) read only 1 byte (the svd2rust API only allows
  213. // reading a half-word)
  214. return unsafe { ptr::read_volatile(&self.spi.dr as *const _ as *const FrameSize) };
  215. }
  216. fn write_data_reg(&mut self, data: FrameSize) {
  217. // NOTE(write_volatile) see note above
  218. unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut FrameSize, data) }
  219. }
  220. // Implement write as per the "Transmit only procedure" page 712
  221. // of RM0008 Rev 20. This is more than twice as fast as the
  222. // default Write<> implementation (which reads and drops each
  223. // received value)
  224. fn spi_write(&mut self, words: &[FrameSize]) -> Result<(), Error> {
  225. // Write each word when the tx buffer is empty
  226. for word in words {
  227. loop {
  228. let sr = self.spi.sr.read();
  229. if sr.txe().bit_is_set() {
  230. // NOTE(write_volatile) see note above
  231. // unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut u8, *word) }
  232. self.write_data_reg(*word);
  233. if sr.modf().bit_is_set() {
  234. return Err(Error::ModeFault);
  235. }
  236. break;
  237. }
  238. }
  239. }
  240. // Wait for final TXE
  241. loop {
  242. let sr = self.spi.sr.read();
  243. if sr.txe().bit_is_set() {
  244. break;
  245. }
  246. }
  247. // Wait for final !BSY
  248. loop {
  249. let sr = self.spi.sr.read();
  250. if !sr.bsy().bit_is_set() {
  251. break;
  252. }
  253. }
  254. // Clear OVR set due to dropped received values
  255. // NOTE(read_volatile) see note above
  256. // unsafe {
  257. // let _ = ptr::read_volatile(&self.spi.dr as *const _ as *const u8);
  258. // }
  259. let _ = self.read_data_reg();
  260. let _ = self.spi.sr.read();
  261. Ok(())
  262. }
  263. }
  264. impl<SPI, REMAP, PINS, FrameSize> Spi<SPI, REMAP, PINS, FrameSize>
  265. where
  266. SPI: Deref<Target = SpiRegisterBlock>,
  267. FrameSize: Copy,
  268. {
  269. #[deprecated(since = "0.6.0", note = "Please use release instead")]
  270. pub fn free(self) -> (SPI, PINS) {
  271. self.release()
  272. }
  273. pub fn release(self) -> (SPI, PINS) {
  274. (self.spi, self.pins)
  275. }
  276. }
  277. impl<SPI, REMAP, PINS> Spi<SPI, REMAP, PINS, u8>
  278. where
  279. SPI: Deref<Target = SpiRegisterBlock> + Enable + Reset,
  280. SPI::Bus: GetBusFreq,
  281. {
  282. fn _spi(
  283. spi: SPI,
  284. pins: PINS,
  285. mode: Mode,
  286. freq: Hertz,
  287. clocks: Clocks,
  288. apb: &mut SPI::Bus,
  289. ) -> Self {
  290. // enable or reset SPI
  291. SPI::enable(apb);
  292. SPI::reset(apb);
  293. // disable SS output
  294. spi.cr2.write(|w| w.ssoe().clear_bit());
  295. let br = match SPI::Bus::get_frequency(&clocks).0 / freq.0 {
  296. 0 => unreachable!(),
  297. 1..=2 => 0b000,
  298. 3..=5 => 0b001,
  299. 6..=11 => 0b010,
  300. 12..=23 => 0b011,
  301. 24..=47 => 0b100,
  302. 48..=95 => 0b101,
  303. 96..=191 => 0b110,
  304. _ => 0b111,
  305. };
  306. spi.cr1.write(|w| {
  307. w
  308. // clock phase from config
  309. .cpha()
  310. .bit(mode.phase == Phase::CaptureOnSecondTransition)
  311. // clock polarity from config
  312. .cpol()
  313. .bit(mode.polarity == Polarity::IdleHigh)
  314. // mstr: master configuration
  315. .mstr()
  316. .set_bit()
  317. // baudrate value
  318. .br()
  319. .bits(br)
  320. // lsbfirst: MSB first
  321. .lsbfirst()
  322. .clear_bit()
  323. // ssm: enable software slave management (NSS pin free for other uses)
  324. .ssm()
  325. .set_bit()
  326. // ssi: set nss high = master mode
  327. .ssi()
  328. .set_bit()
  329. // dff: 8 bit frames
  330. .dff()
  331. .clear_bit()
  332. // bidimode: 2-line unidirectional
  333. .bidimode()
  334. .clear_bit()
  335. // both TX and RX are used
  336. .rxonly()
  337. .clear_bit()
  338. // spe: enable the SPI bus
  339. .spe()
  340. .set_bit()
  341. });
  342. Spi {
  343. spi,
  344. pins,
  345. _remap: PhantomData,
  346. _framesize: PhantomData,
  347. }
  348. }
  349. /// Converts from 8bit dataframe to 16bit.
  350. pub fn frame_size_16bit(self) -> Spi<SPI, REMAP, PINS, u16> {
  351. self.spi.cr1.modify(|_, w| w.spe().clear_bit());
  352. self.spi.cr1.modify(|_, w| w.dff().set_bit());
  353. self.spi.cr1.modify(|_, w| w.spe().set_bit());
  354. Spi {
  355. spi: self.spi,
  356. pins: self.pins,
  357. _remap: PhantomData,
  358. _framesize: PhantomData,
  359. }
  360. }
  361. }
  362. impl<SPI, REMAP, PINS> Spi<SPI, REMAP, PINS, u16>
  363. where
  364. SPI: Deref<Target = SpiRegisterBlock>,
  365. {
  366. /// Converts from 16bit dataframe to 8bit.
  367. pub fn frame_size_8bit(self) -> Spi<SPI, REMAP, PINS, u8> {
  368. self.spi.cr1.modify(|_, w| w.spe().clear_bit());
  369. self.spi.cr1.modify(|_, w| w.dff().clear_bit());
  370. self.spi.cr1.modify(|_, w| w.spe().set_bit());
  371. Spi {
  372. spi: self.spi,
  373. pins: self.pins,
  374. _remap: PhantomData,
  375. _framesize: PhantomData,
  376. }
  377. }
  378. }
  379. impl<SPI, REMAP, PINS, FrameSize> crate::hal::spi::FullDuplex<FrameSize>
  380. for Spi<SPI, REMAP, PINS, FrameSize>
  381. where
  382. SPI: Deref<Target = SpiRegisterBlock>,
  383. FrameSize: Copy,
  384. {
  385. type Error = Error;
  386. fn read(&mut self) -> nb::Result<FrameSize, Error> {
  387. let sr = self.spi.sr.read();
  388. Err(if sr.ovr().bit_is_set() {
  389. nb::Error::Other(Error::Overrun)
  390. } else if sr.modf().bit_is_set() {
  391. nb::Error::Other(Error::ModeFault)
  392. } else if sr.crcerr().bit_is_set() {
  393. nb::Error::Other(Error::Crc)
  394. } else if sr.rxne().bit_is_set() {
  395. // NOTE(read_volatile) read only 1 byte (the svd2rust API only allows
  396. // reading a half-word)
  397. return Ok(self.read_data_reg());
  398. } else {
  399. nb::Error::WouldBlock
  400. })
  401. }
  402. fn send(&mut self, data: FrameSize) -> nb::Result<(), Error> {
  403. let sr = self.spi.sr.read();
  404. Err(if sr.ovr().bit_is_set() {
  405. nb::Error::Other(Error::Overrun)
  406. } else if sr.modf().bit_is_set() {
  407. nb::Error::Other(Error::ModeFault)
  408. } else if sr.crcerr().bit_is_set() {
  409. nb::Error::Other(Error::Crc)
  410. } else if sr.txe().bit_is_set() {
  411. // NOTE(write_volatile) see note above
  412. self.write_data_reg(data);
  413. return Ok(());
  414. } else {
  415. nb::Error::WouldBlock
  416. })
  417. }
  418. }
  419. impl<SPI, REMAP, PINS, FrameSize> crate::hal::blocking::spi::transfer::Default<FrameSize>
  420. for Spi<SPI, REMAP, PINS, FrameSize>
  421. where
  422. SPI: Deref<Target = SpiRegisterBlock>,
  423. FrameSize: Copy,
  424. {
  425. }
  426. impl<SPI, REMAP, PINS> crate::hal::blocking::spi::Write<u8> for Spi<SPI, REMAP, PINS, u8>
  427. where
  428. SPI: Deref<Target = SpiRegisterBlock>,
  429. {
  430. type Error = Error;
  431. // Implement write as per the "Transmit only procedure" page 712
  432. // of RM0008 Rev 20. This is more than twice as fast as the
  433. // default Write<> implementation (which reads and drops each
  434. // received value)
  435. fn write(&mut self, words: &[u8]) -> Result<(), Error> {
  436. self.spi_write(words)
  437. }
  438. }
  439. impl<SPI, REMAP, PINS> crate::hal::blocking::spi::Write<u16> for Spi<SPI, REMAP, PINS, u16>
  440. where
  441. SPI: Deref<Target = SpiRegisterBlock>,
  442. {
  443. type Error = Error;
  444. fn write(&mut self, words: &[u16]) -> Result<(), Error> {
  445. self.spi_write(words)
  446. }
  447. }
  448. // DMA
  449. pub struct SpiPayload<SPI, REMAP, PINS> {
  450. spi: Spi<SPI, REMAP, PINS, u8>,
  451. }
  452. pub type SpiTxDma<SPI, REMAP, PINS, CHANNEL> = TxDma<SpiPayload<SPI, REMAP, PINS>, CHANNEL>;
  453. macro_rules! spi_dma {
  454. ($SPIi:ident, $TCi:ident) => {
  455. impl<REMAP, PINS> Transmit for SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  456. type TxChannel = $TCi;
  457. type ReceivedWord = u8;
  458. }
  459. impl<REMAP, PINS> Spi<$SPIi, REMAP, PINS, u8> {
  460. pub fn with_tx_dma(self, channel: $TCi) -> SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  461. let payload = SpiPayload { spi: self };
  462. SpiTxDma { payload, channel }
  463. }
  464. }
  465. impl<REMAP, PINS> TransferPayload for SpiTxDma<$SPIi, REMAP, PINS, $TCi> {
  466. fn start(&mut self) {
  467. self.payload
  468. .spi
  469. .spi
  470. .cr2
  471. .modify(|_, w| w.txdmaen().set_bit());
  472. self.channel.start();
  473. }
  474. fn stop(&mut self) {
  475. self.payload
  476. .spi
  477. .spi
  478. .cr2
  479. .modify(|_, w| w.txdmaen().clear_bit());
  480. self.channel.stop();
  481. }
  482. }
  483. impl<A, B, REMAP, PIN> crate::dma::WriteDma<A, B, u8> for SpiTxDma<$SPIi, REMAP, PIN, $TCi>
  484. where
  485. A: AsSlice<Element = u8>,
  486. B: Static<A>,
  487. {
  488. fn write(mut self, buffer: B) -> Transfer<R, B, Self> {
  489. {
  490. let buffer = buffer.borrow().as_slice();
  491. self.channel.set_peripheral_address(
  492. unsafe { &(*$SPIi::ptr()).dr as *const _ as u32 },
  493. false,
  494. );
  495. self.channel
  496. .set_memory_address(buffer.as_ptr() as u32, true);
  497. self.channel.set_transfer_length(buffer.len());
  498. }
  499. atomic::compiler_fence(Ordering::Release);
  500. self.channel.ch().cr.modify(|_, w| {
  501. w
  502. // memory to memory mode disabled
  503. .mem2mem()
  504. .clear_bit()
  505. // medium channel priority level
  506. .pl()
  507. .medium()
  508. // 8-bit memory size
  509. .msize()
  510. .bits8()
  511. // 8-bit peripheral size
  512. .psize()
  513. .bits8()
  514. // circular mode disabled
  515. .circ()
  516. .clear_bit()
  517. // read from memory
  518. .dir()
  519. .set_bit()
  520. });
  521. self.start();
  522. Transfer::r(buffer, self)
  523. }
  524. }
  525. };
  526. }
  527. spi_dma!(SPI1, C3);
  528. spi_dma!(SPI2, C5);
  529. #[cfg(feature = "connectivity")]
  530. spi_dma!(SPI3, C2);