spi.rs 18 KB

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