i2c.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. //! Inter-Integrated Circuit (I2C) bus
  2. // This document describes a correct i2c implementation and is what
  3. // parts of this code is based on
  4. // https://www.st.com/content/ccc/resource/technical/document/application_note/5d/ae/a3/6f/08/69/4e/9b/CD00209826.pdf/files/CD00209826.pdf/jcr:content/translations/en.CD00209826.pdf
  5. use crate::afio::MAPR;
  6. use crate::gpio::gpiob::{PB10, PB11, PB6, PB7, PB8, PB9};
  7. use crate::gpio::{Alternate, OpenDrain};
  8. use crate::hal::blocking::i2c::{Read, Write, WriteRead};
  9. use crate::pac::{DWT, I2C1, I2C2};
  10. use crate::rcc::{Clocks, Enable, GetBusFreq, Reset, APB1};
  11. use crate::time::Hertz;
  12. use core::ops::Deref;
  13. use nb::Error::{Other, WouldBlock};
  14. use nb::{Error as NbError, Result as NbResult};
  15. /// I2C error
  16. #[derive(Debug, Eq, PartialEq)]
  17. pub enum Error {
  18. /// Bus error
  19. Bus,
  20. /// Arbitration loss
  21. Arbitration,
  22. /// No ack received
  23. Acknowledge,
  24. /// Overrun/underrun
  25. Overrun,
  26. // Pec, // SMBUS mode only
  27. // Timeout, // SMBUS mode only
  28. // Alert, // SMBUS mode only
  29. #[doc(hidden)]
  30. _Extensible,
  31. }
  32. #[derive(Debug, Eq, PartialEq)]
  33. pub enum DutyCycle {
  34. Ratio2to1,
  35. Ratio16to9,
  36. }
  37. #[derive(Debug, PartialEq)]
  38. pub enum Mode {
  39. Standard {
  40. frequency: Hertz,
  41. },
  42. Fast {
  43. frequency: Hertz,
  44. duty_cycle: DutyCycle,
  45. },
  46. }
  47. impl Mode {
  48. pub fn standard<F: Into<Hertz>>(frequency: F) -> Self {
  49. Mode::Standard {
  50. frequency: frequency.into(),
  51. }
  52. }
  53. pub fn fast<F: Into<Hertz>>(frequency: F, duty_cycle: DutyCycle) -> Self {
  54. Mode::Fast {
  55. frequency: frequency.into(),
  56. duty_cycle,
  57. }
  58. }
  59. pub fn get_frequency(&self) -> Hertz {
  60. match *self {
  61. Mode::Standard { frequency } => frequency,
  62. Mode::Fast { frequency, .. } => frequency,
  63. }
  64. }
  65. }
  66. /// Helper trait to ensure that the correct I2C pins are used for the corresponding interface
  67. pub trait Pins<I2C> {
  68. const REMAP: bool;
  69. }
  70. impl Pins<I2C1> for (PB6<Alternate<OpenDrain>>, PB7<Alternate<OpenDrain>>) {
  71. const REMAP: bool = false;
  72. }
  73. impl Pins<I2C1> for (PB8<Alternate<OpenDrain>>, PB9<Alternate<OpenDrain>>) {
  74. const REMAP: bool = true;
  75. }
  76. impl Pins<I2C2> for (PB10<Alternate<OpenDrain>>, PB11<Alternate<OpenDrain>>) {
  77. const REMAP: bool = false;
  78. }
  79. /// I2C peripheral operating in master mode
  80. pub struct I2c<I2C, PINS> {
  81. i2c: I2C,
  82. pins: PINS,
  83. mode: Mode,
  84. pclk1: u32,
  85. }
  86. /// embedded-hal compatible blocking I2C implementation
  87. ///
  88. /// **NOTE**: Before using blocking I2C, you need to enable the DWT cycle counter using the
  89. /// [DWT::enable_cycle_counter] method.
  90. pub struct BlockingI2c<I2C, PINS> {
  91. nb: I2c<I2C, PINS>,
  92. start_timeout: u32,
  93. start_retries: u8,
  94. addr_timeout: u32,
  95. data_timeout: u32,
  96. }
  97. impl<PINS> I2c<I2C1, PINS> {
  98. /// Creates a generic I2C1 object on pins PB6 and PB7 or PB8 and PB9 (if remapped)
  99. pub fn i2c1(
  100. i2c: I2C1,
  101. pins: PINS,
  102. mapr: &mut MAPR,
  103. mode: Mode,
  104. clocks: Clocks,
  105. apb: &mut APB1,
  106. ) -> Self
  107. where
  108. PINS: Pins<I2C1>,
  109. {
  110. mapr.modify_mapr(|_, w| w.i2c1_remap().bit(PINS::REMAP));
  111. I2c::<I2C1, _>::_i2c(i2c, pins, mode, clocks, apb)
  112. }
  113. }
  114. impl<PINS> BlockingI2c<I2C1, PINS> {
  115. /// Creates a blocking I2C1 object on pins PB6 and PB7 or PB8 and PB9 using the embedded-hal `BlockingI2c` trait.
  116. pub fn i2c1(
  117. i2c: I2C1,
  118. pins: PINS,
  119. mapr: &mut MAPR,
  120. mode: Mode,
  121. clocks: Clocks,
  122. apb: &mut APB1,
  123. start_timeout_us: u32,
  124. start_retries: u8,
  125. addr_timeout_us: u32,
  126. data_timeout_us: u32,
  127. ) -> Self
  128. where
  129. PINS: Pins<I2C1>,
  130. {
  131. mapr.modify_mapr(|_, w| w.i2c1_remap().bit(PINS::REMAP));
  132. BlockingI2c::<I2C1, _>::_i2c(
  133. i2c,
  134. pins,
  135. mode,
  136. clocks,
  137. apb,
  138. start_timeout_us,
  139. start_retries,
  140. addr_timeout_us,
  141. data_timeout_us,
  142. )
  143. }
  144. }
  145. impl<PINS> I2c<I2C2, PINS> {
  146. /// Creates a generic I2C2 object on pins PB10 and PB11 using the embedded-hal `BlockingI2c` trait.
  147. pub fn i2c2(i2c: I2C2, pins: PINS, mode: Mode, clocks: Clocks, apb: &mut APB1) -> Self
  148. where
  149. PINS: Pins<I2C2>,
  150. {
  151. I2c::<I2C2, _>::_i2c(i2c, pins, mode, clocks, apb)
  152. }
  153. }
  154. impl<PINS> BlockingI2c<I2C2, PINS> {
  155. /// Creates a blocking I2C2 object on pins PB10 and PB1
  156. pub fn i2c2(
  157. i2c: I2C2,
  158. pins: PINS,
  159. mode: Mode,
  160. clocks: Clocks,
  161. apb: &mut APB1,
  162. start_timeout_us: u32,
  163. start_retries: u8,
  164. addr_timeout_us: u32,
  165. data_timeout_us: u32,
  166. ) -> Self
  167. where
  168. PINS: Pins<I2C2>,
  169. {
  170. BlockingI2c::<I2C2, _>::_i2c(
  171. i2c,
  172. pins,
  173. mode,
  174. clocks,
  175. apb,
  176. start_timeout_us,
  177. start_retries,
  178. addr_timeout_us,
  179. data_timeout_us,
  180. )
  181. }
  182. }
  183. /// Generates a blocking I2C instance from a universal I2C object
  184. fn blocking_i2c<I2C, PINS>(
  185. i2c: I2c<I2C, PINS>,
  186. clocks: Clocks,
  187. start_timeout_us: u32,
  188. start_retries: u8,
  189. addr_timeout_us: u32,
  190. data_timeout_us: u32,
  191. ) -> BlockingI2c<I2C, PINS> {
  192. let sysclk_mhz = clocks.sysclk().0 / 1_000_000;
  193. BlockingI2c {
  194. nb: i2c,
  195. start_timeout: start_timeout_us * sysclk_mhz,
  196. start_retries,
  197. addr_timeout: addr_timeout_us * sysclk_mhz,
  198. data_timeout: data_timeout_us * sysclk_mhz,
  199. }
  200. }
  201. macro_rules! wait_for_flag {
  202. ($i2c:expr, $flag:ident) => {{
  203. let sr1 = $i2c.sr1.read();
  204. if sr1.berr().bit_is_set() {
  205. $i2c.sr1.write(|w| w.berr().clear_bit());
  206. Err(Other(Error::Bus))
  207. } else if sr1.arlo().bit_is_set() {
  208. $i2c.sr1.write(|w| w.arlo().clear_bit());
  209. Err(Other(Error::Arbitration))
  210. } else if sr1.af().bit_is_set() {
  211. $i2c.sr1.write(|w| w.af().clear_bit());
  212. Err(Other(Error::Acknowledge))
  213. } else if sr1.ovr().bit_is_set() {
  214. $i2c.sr1.write(|w| w.ovr().clear_bit());
  215. Err(Other(Error::Overrun))
  216. } else if sr1.$flag().bit_is_set() {
  217. Ok(())
  218. } else {
  219. Err(WouldBlock)
  220. }
  221. }};
  222. }
  223. macro_rules! busy_wait {
  224. ($nb_expr:expr, $exit_cond:expr) => {{
  225. loop {
  226. let res = $nb_expr;
  227. if res != Err(WouldBlock) {
  228. break res;
  229. }
  230. if $exit_cond {
  231. break res;
  232. }
  233. }
  234. }};
  235. }
  236. macro_rules! busy_wait_cycles {
  237. ($nb_expr:expr, $cycles:expr) => {{
  238. let started = DWT::get_cycle_count();
  239. let cycles = $cycles;
  240. busy_wait!(
  241. $nb_expr,
  242. DWT::get_cycle_count().wrapping_sub(started) >= cycles
  243. )
  244. }};
  245. }
  246. pub type I2cRegisterBlock = crate::pac::i2c1::RegisterBlock;
  247. impl<I2C, PINS> I2c<I2C, PINS>
  248. where
  249. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  250. I2C::Bus: GetBusFreq,
  251. {
  252. /// Configures the I2C peripheral to work in master mode
  253. fn _i2c(i2c: I2C, pins: PINS, mode: Mode, clocks: Clocks, apb: &mut I2C::Bus) -> Self {
  254. I2C::enable(apb);
  255. I2C::reset(apb);
  256. let pclk1 = I2C::Bus::get_frequency(&clocks).0;
  257. assert!(mode.get_frequency().0 <= 400_000);
  258. let mut i2c = I2c {
  259. i2c,
  260. pins,
  261. mode,
  262. pclk1,
  263. };
  264. i2c.init();
  265. i2c
  266. }
  267. }
  268. impl<I2C, PINS> I2c<I2C, PINS>
  269. where
  270. I2C: Deref<Target = I2cRegisterBlock>,
  271. {
  272. /// Initializes I2C. Configures the `I2C_TRISE`, `I2C_CRX`, and `I2C_CCR` registers
  273. /// according to the system frequency and I2C mode.
  274. fn init(&mut self) {
  275. let freq = self.mode.get_frequency();
  276. let pclk1_mhz = (self.pclk1 / 1000000) as u16;
  277. self.i2c
  278. .cr2
  279. .write(|w| unsafe { w.freq().bits(pclk1_mhz as u8) });
  280. self.i2c.cr1.write(|w| w.pe().clear_bit());
  281. match self.mode {
  282. Mode::Standard { .. } => {
  283. self.i2c
  284. .trise
  285. .write(|w| w.trise().bits((pclk1_mhz + 1) as u8));
  286. self.i2c.ccr.write(|w| unsafe {
  287. w.ccr().bits(((self.pclk1 / (freq.0 * 2)) as u16).max(4))
  288. });
  289. }
  290. Mode::Fast { ref duty_cycle, .. } => {
  291. self.i2c
  292. .trise
  293. .write(|w| w.trise().bits((pclk1_mhz * 300 / 1000 + 1) as u8));
  294. self.i2c.ccr.write(|w| {
  295. let (freq, duty) = match duty_cycle {
  296. &DutyCycle::Ratio2to1 => {
  297. (((self.pclk1 / (freq.0 * 3)) as u16).max(1), false)
  298. }
  299. &DutyCycle::Ratio16to9 => {
  300. (((self.pclk1 / (freq.0 * 25)) as u16).max(1), true)
  301. }
  302. };
  303. unsafe { w.ccr().bits(freq).duty().bit(duty).f_s().set_bit() }
  304. });
  305. }
  306. };
  307. self.i2c.cr1.modify(|_, w| w.pe().set_bit());
  308. }
  309. /// Perform an I2C software reset
  310. fn reset(&mut self) {
  311. self.i2c.cr1.write(|w| w.pe().set_bit().swrst().set_bit());
  312. self.i2c.cr1.reset();
  313. self.init();
  314. }
  315. /// Generate START condition
  316. fn send_start(&mut self) {
  317. self.i2c.cr1.modify(|_, w| w.start().set_bit());
  318. }
  319. /// Check if START condition is generated. If the condition is not generated, this
  320. /// method returns `WouldBlock` so the program can act accordingly
  321. /// (busy wait, async, ...)
  322. fn wait_after_sent_start(&mut self) -> NbResult<(), Error> {
  323. wait_for_flag!(self.i2c, sb)
  324. }
  325. /// Check if STOP condition is generated. If the condition is not generated, this
  326. /// method returns `WouldBlock` so the program can act accordingly
  327. /// (busy wait, async, ...)
  328. fn wait_for_stop(&mut self) -> NbResult<(), Error> {
  329. if self.i2c.cr1.read().stop().is_no_stop() {
  330. Ok(())
  331. } else {
  332. Err(WouldBlock)
  333. }
  334. }
  335. /// Sends the (7-Bit) address on the I2C bus. The 8th bit on the bus is set
  336. /// depending on wether it is a read or write transfer.
  337. fn send_addr(&self, addr: u8, read: bool) {
  338. self.i2c
  339. .dr
  340. .write(|w| w.dr().bits(addr << 1 | (if read { 1 } else { 0 })));
  341. }
  342. /// Generate STOP condition
  343. fn send_stop(&self) {
  344. self.i2c.cr1.modify(|_, w| w.stop().set_bit());
  345. }
  346. /// Releases the I2C peripheral and associated pins
  347. pub fn free(self) -> (I2C, PINS) {
  348. (self.i2c, self.pins)
  349. }
  350. }
  351. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  352. where
  353. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  354. I2C::Bus: GetBusFreq,
  355. {
  356. fn _i2c(
  357. i2c: I2C,
  358. pins: PINS,
  359. mode: Mode,
  360. clocks: Clocks,
  361. apb: &mut I2C::Bus,
  362. start_timeout_us: u32,
  363. start_retries: u8,
  364. addr_timeout_us: u32,
  365. data_timeout_us: u32,
  366. ) -> Self {
  367. blocking_i2c(
  368. I2c::<I2C, _>::_i2c(i2c, pins, mode, clocks, apb),
  369. clocks,
  370. start_timeout_us,
  371. start_retries,
  372. addr_timeout_us,
  373. data_timeout_us,
  374. )
  375. }
  376. }
  377. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  378. where
  379. I2C: Deref<Target = I2cRegisterBlock>,
  380. {
  381. fn send_start_and_wait(&mut self) -> NbResult<(), Error> {
  382. // According to http://www.st.com/content/ccc/resource/technical/document/errata_sheet/f5/50/c9/46/56/db/4a/f6/CD00197763.pdf/files/CD00197763.pdf/jcr:content/translations/en.CD00197763.pdf
  383. // 2.14.4 Wrong behavior of I2C peripheral in master mode after a misplaced STOP
  384. let mut retries_left = self.start_retries;
  385. let mut last_ret: NbResult<(), Error> = Err(WouldBlock);
  386. while retries_left > 0 {
  387. self.nb.send_start();
  388. last_ret = busy_wait_cycles!(self.nb.wait_after_sent_start(), self.start_timeout);
  389. if let Err(_) = last_ret {
  390. self.nb.reset();
  391. } else {
  392. break;
  393. }
  394. retries_left -= 1;
  395. }
  396. last_ret
  397. }
  398. fn send_addr_and_wait(&mut self, addr: u8, read: bool) -> NbResult<(), Error> {
  399. self.nb.i2c.sr1.read();
  400. self.nb.send_addr(addr, read);
  401. let ret = busy_wait_cycles!(wait_for_flag!(self.nb.i2c, addr), self.addr_timeout);
  402. if ret == Err(Other(Error::Acknowledge)) {
  403. self.nb.send_stop();
  404. }
  405. ret
  406. }
  407. fn write_bytes_and_wait(&mut self, bytes: &[u8]) -> NbResult<(), Error> {
  408. self.nb.i2c.sr1.read();
  409. self.nb.i2c.sr2.read();
  410. self.nb.i2c.dr.write(|w| w.dr().bits(bytes[0]));
  411. for byte in &bytes[1..] {
  412. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, tx_e), self.data_timeout)?;
  413. self.nb.i2c.dr.write(|w| w.dr().bits(*byte));
  414. }
  415. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  416. Ok(())
  417. }
  418. fn write_without_stop(&mut self, addr: u8, bytes: &[u8]) -> NbResult<(), Error> {
  419. self.send_start_and_wait()?;
  420. self.send_addr_and_wait(addr, false)?;
  421. let ret = self.write_bytes_and_wait(bytes);
  422. if ret == Err(Other(Error::Acknowledge)) {
  423. self.nb.send_stop();
  424. }
  425. ret
  426. }
  427. }
  428. impl<I2C, PINS> Write for BlockingI2c<I2C, PINS>
  429. where
  430. I2C: Deref<Target = I2cRegisterBlock>,
  431. {
  432. type Error = NbError<Error>;
  433. fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
  434. self.write_without_stop(addr, bytes)?;
  435. self.nb.send_stop();
  436. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  437. Ok(())
  438. }
  439. }
  440. impl<I2C, PINS> Read for BlockingI2c<I2C, PINS>
  441. where
  442. I2C: Deref<Target = I2cRegisterBlock>,
  443. {
  444. type Error = NbError<Error>;
  445. fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
  446. self.send_start_and_wait()?;
  447. self.send_addr_and_wait(addr, true)?;
  448. match buffer.len() {
  449. 1 => {
  450. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  451. self.nb.i2c.sr1.read();
  452. self.nb.i2c.sr2.read();
  453. self.nb.send_stop();
  454. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  455. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  456. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  457. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  458. }
  459. 2 => {
  460. self.nb
  461. .i2c
  462. .cr1
  463. .modify(|_, w| w.pos().set_bit().ack().set_bit());
  464. self.nb.i2c.sr1.read();
  465. self.nb.i2c.sr2.read();
  466. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  467. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  468. self.nb.send_stop();
  469. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  470. buffer[1] = self.nb.i2c.dr.read().dr().bits();
  471. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  472. self.nb
  473. .i2c
  474. .cr1
  475. .modify(|_, w| w.pos().clear_bit().ack().clear_bit());
  476. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  477. }
  478. buffer_len => {
  479. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  480. self.nb.i2c.sr1.read();
  481. self.nb.i2c.sr2.read();
  482. let (first_bytes, last_two_bytes) = buffer.split_at_mut(buffer_len - 3);
  483. for byte in first_bytes {
  484. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  485. *byte = self.nb.i2c.dr.read().dr().bits();
  486. }
  487. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  488. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  489. last_two_bytes[0] = self.nb.i2c.dr.read().dr().bits();
  490. self.nb.send_stop();
  491. last_two_bytes[1] = self.nb.i2c.dr.read().dr().bits();
  492. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  493. last_two_bytes[2] = self.nb.i2c.dr.read().dr().bits();
  494. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  495. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  496. }
  497. }
  498. Ok(())
  499. }
  500. }
  501. impl<I2C, PINS> WriteRead for BlockingI2c<I2C, PINS>
  502. where
  503. I2C: Deref<Target = I2cRegisterBlock>,
  504. {
  505. type Error = NbError<Error>;
  506. fn write_read(&mut self, addr: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> {
  507. if !bytes.is_empty() {
  508. self.write_without_stop(addr, bytes)?;
  509. }
  510. if !buffer.is_empty() {
  511. self.read(addr, buffer)?;
  512. } else if !bytes.is_empty() {
  513. self.nb.send_stop();
  514. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  515. }
  516. Ok(())
  517. }
  518. }