i2c.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. pub struct BlockingI2c<I2C, PINS> {
  88. nb: I2c<I2C, PINS>,
  89. start_timeout: u32,
  90. start_retries: u8,
  91. addr_timeout: u32,
  92. data_timeout: u32,
  93. }
  94. impl<PINS> I2c<I2C1, PINS> {
  95. /// Creates a generic I2C1 object on pins PB6 and PB7 or PB8 and PB9 (if remapped)
  96. pub fn i2c1(
  97. i2c: I2C1,
  98. pins: PINS,
  99. mapr: &mut MAPR,
  100. mode: Mode,
  101. clocks: Clocks,
  102. apb: &mut APB1,
  103. ) -> Self
  104. where
  105. PINS: Pins<I2C1>,
  106. {
  107. mapr.modify_mapr(|_, w| w.i2c1_remap().bit(PINS::REMAP));
  108. I2c::<I2C1, _>::_i2c(i2c, pins, mode, clocks, apb)
  109. }
  110. }
  111. impl<PINS> BlockingI2c<I2C1, PINS> {
  112. /// Creates a blocking I2C1 object on pins PB6 and PB7 or PB8 and PB9 using the embedded-hal `BlockingI2c` trait.
  113. pub fn i2c1(
  114. i2c: I2C1,
  115. pins: PINS,
  116. mapr: &mut MAPR,
  117. mode: Mode,
  118. clocks: Clocks,
  119. apb: &mut APB1,
  120. start_timeout_us: u32,
  121. start_retries: u8,
  122. addr_timeout_us: u32,
  123. data_timeout_us: u32,
  124. ) -> Self
  125. where
  126. PINS: Pins<I2C1>,
  127. {
  128. mapr.modify_mapr(|_, w| w.i2c1_remap().bit(PINS::REMAP));
  129. BlockingI2c::<I2C1, _>::_i2c(
  130. i2c,
  131. pins,
  132. mode,
  133. clocks,
  134. apb,
  135. start_timeout_us,
  136. start_retries,
  137. addr_timeout_us,
  138. data_timeout_us,
  139. )
  140. }
  141. }
  142. impl<PINS> I2c<I2C2, PINS> {
  143. /// Creates a generic I2C2 object on pins PB10 and PB11 using the embedded-hal `BlockingI2c` trait.
  144. pub fn i2c2(i2c: I2C2, pins: PINS, mode: Mode, clocks: Clocks, apb: &mut APB1) -> Self
  145. where
  146. PINS: Pins<I2C2>,
  147. {
  148. I2c::<I2C2, _>::_i2c(i2c, pins, mode, clocks, apb)
  149. }
  150. }
  151. impl<PINS> BlockingI2c<I2C2, PINS> {
  152. /// Creates a blocking I2C2 object on pins PB10 and PB1
  153. pub fn i2c2(
  154. i2c: I2C2,
  155. pins: PINS,
  156. mode: Mode,
  157. clocks: Clocks,
  158. apb: &mut APB1,
  159. start_timeout_us: u32,
  160. start_retries: u8,
  161. addr_timeout_us: u32,
  162. data_timeout_us: u32,
  163. ) -> Self
  164. where
  165. PINS: Pins<I2C2>,
  166. {
  167. BlockingI2c::<I2C2, _>::_i2c(
  168. i2c,
  169. pins,
  170. mode,
  171. clocks,
  172. apb,
  173. start_timeout_us,
  174. start_retries,
  175. addr_timeout_us,
  176. data_timeout_us,
  177. )
  178. }
  179. }
  180. /// Generates a blocking I2C instance from a universal I2C object
  181. fn blocking_i2c<I2C, PINS>(
  182. i2c: I2c<I2C, PINS>,
  183. clocks: Clocks,
  184. start_timeout_us: u32,
  185. start_retries: u8,
  186. addr_timeout_us: u32,
  187. data_timeout_us: u32,
  188. ) -> BlockingI2c<I2C, PINS> {
  189. let sysclk_mhz = clocks.sysclk().0 / 1_000_000;
  190. BlockingI2c {
  191. nb: i2c,
  192. start_timeout: start_timeout_us * sysclk_mhz,
  193. start_retries,
  194. addr_timeout: addr_timeout_us * sysclk_mhz,
  195. data_timeout: data_timeout_us * sysclk_mhz,
  196. }
  197. }
  198. macro_rules! wait_for_flag {
  199. ($i2c:expr, $flag:ident) => {{
  200. let sr1 = $i2c.sr1.read();
  201. if sr1.berr().bit_is_set() {
  202. $i2c.sr1.write(|w| w.berr().clear_bit());
  203. Err(Other(Error::Bus))
  204. } else if sr1.arlo().bit_is_set() {
  205. $i2c.sr1.write(|w| w.arlo().clear_bit());
  206. Err(Other(Error::Arbitration))
  207. } else if sr1.af().bit_is_set() {
  208. $i2c.sr1.write(|w| w.af().clear_bit());
  209. Err(Other(Error::Acknowledge))
  210. } else if sr1.ovr().bit_is_set() {
  211. $i2c.sr1.write(|w| w.ovr().clear_bit());
  212. Err(Other(Error::Overrun))
  213. } else if sr1.$flag().bit_is_set() {
  214. Ok(())
  215. } else {
  216. Err(WouldBlock)
  217. }
  218. }};
  219. }
  220. macro_rules! busy_wait {
  221. ($nb_expr:expr, $exit_cond:expr) => {{
  222. loop {
  223. let res = $nb_expr;
  224. if res != Err(WouldBlock) {
  225. break res;
  226. }
  227. if $exit_cond {
  228. break res;
  229. }
  230. }
  231. }};
  232. }
  233. macro_rules! busy_wait_cycles {
  234. ($nb_expr:expr, $cycles:expr) => {{
  235. let started = DWT::get_cycle_count();
  236. let cycles = $cycles;
  237. busy_wait!(
  238. $nb_expr,
  239. DWT::get_cycle_count().wrapping_sub(started) >= cycles
  240. )
  241. }};
  242. }
  243. pub type I2cRegisterBlock = crate::pac::i2c1::RegisterBlock;
  244. impl<I2C, PINS> I2c<I2C, PINS>
  245. where
  246. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  247. I2C::Bus: GetBusFreq,
  248. {
  249. /// Configures the I2C peripheral to work in master mode
  250. fn _i2c(i2c: I2C, pins: PINS, mode: Mode, clocks: Clocks, apb: &mut I2C::Bus) -> Self {
  251. I2C::enable(apb);
  252. I2C::reset(apb);
  253. let pclk1 = I2C::Bus::get_frequency(&clocks).0;
  254. assert!(mode.get_frequency().0 <= 400_000);
  255. let mut i2c = I2c {
  256. i2c,
  257. pins,
  258. mode,
  259. pclk1,
  260. };
  261. i2c.init();
  262. i2c
  263. }
  264. }
  265. impl<I2C, PINS> I2c<I2C, PINS>
  266. where
  267. I2C: Deref<Target = I2cRegisterBlock>,
  268. {
  269. /// Initializes I2C. Configures the `I2C_TRISE`, `I2C_CRX`, and `I2C_CCR` registers
  270. /// according to the system frequency and I2C mode.
  271. fn init(&mut self) {
  272. let freq = self.mode.get_frequency();
  273. let pclk1_mhz = (self.pclk1 / 1000000) as u16;
  274. self.i2c
  275. .cr2
  276. .write(|w| unsafe { w.freq().bits(pclk1_mhz as u8) });
  277. self.i2c.cr1.write(|w| w.pe().clear_bit());
  278. match self.mode {
  279. Mode::Standard { .. } => {
  280. self.i2c
  281. .trise
  282. .write(|w| w.trise().bits((pclk1_mhz + 1) as u8));
  283. self.i2c.ccr.write(|w| unsafe {
  284. w.ccr().bits(((self.pclk1 / (freq.0 * 2)) as u16).max(4))
  285. });
  286. }
  287. Mode::Fast { ref duty_cycle, .. } => {
  288. self.i2c
  289. .trise
  290. .write(|w| w.trise().bits((pclk1_mhz * 300 / 1000 + 1) as u8));
  291. self.i2c.ccr.write(|w| {
  292. let (freq, duty) = match duty_cycle {
  293. &DutyCycle::Ratio2to1 => {
  294. (((self.pclk1 / (freq.0 * 3)) as u16).max(1), false)
  295. }
  296. &DutyCycle::Ratio16to9 => {
  297. (((self.pclk1 / (freq.0 * 25)) as u16).max(1), true)
  298. }
  299. };
  300. unsafe { w.ccr().bits(freq).duty().bit(duty).f_s().set_bit() }
  301. });
  302. }
  303. };
  304. self.i2c.cr1.modify(|_, w| w.pe().set_bit());
  305. }
  306. /// Perform an I2C software reset
  307. fn reset(&mut self) {
  308. self.i2c.cr1.write(|w| w.pe().set_bit().swrst().set_bit());
  309. self.i2c.cr1.reset();
  310. self.init();
  311. }
  312. /// Generate START condition
  313. fn send_start(&mut self) {
  314. self.i2c.cr1.modify(|_, w| w.start().set_bit());
  315. }
  316. /// Check if START condition is generated. If the condition is not generated, this
  317. /// method returns `WouldBlock` so the program can act accordingly
  318. /// (busy wait, async, ...)
  319. fn wait_after_sent_start(&mut self) -> NbResult<(), Error> {
  320. wait_for_flag!(self.i2c, sb)
  321. }
  322. /// Check if STOP condition is generated. If the condition is not generated, this
  323. /// method returns `WouldBlock` so the program can act accordingly
  324. /// (busy wait, async, ...)
  325. fn wait_for_stop(&mut self) -> NbResult<(), Error> {
  326. if self.i2c.cr1.read().stop().is_no_stop() {
  327. Ok(())
  328. } else {
  329. Err(WouldBlock)
  330. }
  331. }
  332. /// Sends the (7-Bit) address on the I2C bus. The 8th bit on the bus is set
  333. /// depending on wether it is a read or write transfer.
  334. fn send_addr(&self, addr: u8, read: bool) {
  335. self.i2c
  336. .dr
  337. .write(|w| w.dr().bits(addr << 1 | (if read { 1 } else { 0 })));
  338. }
  339. /// Generate STOP condition
  340. fn send_stop(&self) {
  341. self.i2c.cr1.modify(|_, w| w.stop().set_bit());
  342. }
  343. /// Releases the I2C peripheral and associated pins
  344. pub fn free(self) -> (I2C, PINS) {
  345. (self.i2c, self.pins)
  346. }
  347. }
  348. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  349. where
  350. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  351. I2C::Bus: GetBusFreq,
  352. {
  353. fn _i2c(
  354. i2c: I2C,
  355. pins: PINS,
  356. mode: Mode,
  357. clocks: Clocks,
  358. apb: &mut I2C::Bus,
  359. start_timeout_us: u32,
  360. start_retries: u8,
  361. addr_timeout_us: u32,
  362. data_timeout_us: u32,
  363. ) -> Self {
  364. blocking_i2c(
  365. I2c::<I2C, _>::_i2c(i2c, pins, mode, clocks, apb),
  366. clocks,
  367. start_timeout_us,
  368. start_retries,
  369. addr_timeout_us,
  370. data_timeout_us,
  371. )
  372. }
  373. }
  374. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  375. where
  376. I2C: Deref<Target = I2cRegisterBlock>,
  377. {
  378. fn send_start_and_wait(&mut self) -> NbResult<(), Error> {
  379. // 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
  380. // 2.14.4 Wrong behavior of I2C peripheral in master mode after a misplaced STOP
  381. let mut retries_left = self.start_retries;
  382. let mut last_ret: NbResult<(), Error> = Err(WouldBlock);
  383. while retries_left > 0 {
  384. self.nb.send_start();
  385. last_ret = busy_wait_cycles!(self.nb.wait_after_sent_start(), self.start_timeout);
  386. if let Err(_) = last_ret {
  387. self.nb.reset();
  388. } else {
  389. break;
  390. }
  391. retries_left -= 1;
  392. }
  393. last_ret
  394. }
  395. fn send_addr_and_wait(&mut self, addr: u8, read: bool) -> NbResult<(), Error> {
  396. self.nb.i2c.sr1.read();
  397. self.nb.send_addr(addr, read);
  398. let ret = busy_wait_cycles!(wait_for_flag!(self.nb.i2c, addr), self.addr_timeout);
  399. if ret == Err(Other(Error::Acknowledge)) {
  400. self.nb.send_stop();
  401. }
  402. ret
  403. }
  404. fn write_bytes_and_wait(&mut self, bytes: &[u8]) -> NbResult<(), Error> {
  405. self.nb.i2c.sr1.read();
  406. self.nb.i2c.sr2.read();
  407. self.nb.i2c.dr.write(|w| w.dr().bits(bytes[0]));
  408. for byte in &bytes[1..] {
  409. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, tx_e), self.data_timeout)?;
  410. self.nb.i2c.dr.write(|w| w.dr().bits(*byte));
  411. }
  412. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  413. Ok(())
  414. }
  415. fn write_without_stop(&mut self, addr: u8, bytes: &[u8]) -> NbResult<(), Error> {
  416. self.send_start_and_wait()?;
  417. self.send_addr_and_wait(addr, false)?;
  418. let ret = self.write_bytes_and_wait(bytes);
  419. if ret == Err(Other(Error::Acknowledge)) {
  420. self.nb.send_stop();
  421. }
  422. ret
  423. }
  424. }
  425. impl<I2C, PINS> Write for BlockingI2c<I2C, PINS>
  426. where
  427. I2C: Deref<Target = I2cRegisterBlock>,
  428. {
  429. type Error = NbError<Error>;
  430. fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
  431. self.write_without_stop(addr, bytes)?;
  432. self.nb.send_stop();
  433. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  434. Ok(())
  435. }
  436. }
  437. impl<I2C, PINS> Read for BlockingI2c<I2C, PINS>
  438. where
  439. I2C: Deref<Target = I2cRegisterBlock>,
  440. {
  441. type Error = NbError<Error>;
  442. fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
  443. self.send_start_and_wait()?;
  444. self.send_addr_and_wait(addr, true)?;
  445. match buffer.len() {
  446. 1 => {
  447. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  448. self.nb.i2c.sr1.read();
  449. self.nb.i2c.sr2.read();
  450. self.nb.send_stop();
  451. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  452. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  453. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  454. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  455. }
  456. 2 => {
  457. self.nb
  458. .i2c
  459. .cr1
  460. .modify(|_, w| w.pos().set_bit().ack().set_bit());
  461. self.nb.i2c.sr1.read();
  462. self.nb.i2c.sr2.read();
  463. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  464. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  465. self.nb.send_stop();
  466. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  467. buffer[1] = self.nb.i2c.dr.read().dr().bits();
  468. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  469. self.nb
  470. .i2c
  471. .cr1
  472. .modify(|_, w| w.pos().clear_bit().ack().clear_bit());
  473. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  474. }
  475. buffer_len => {
  476. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  477. self.nb.i2c.sr1.read();
  478. self.nb.i2c.sr2.read();
  479. let (first_bytes, last_two_bytes) = buffer.split_at_mut(buffer_len - 3);
  480. for byte in first_bytes {
  481. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  482. *byte = self.nb.i2c.dr.read().dr().bits();
  483. }
  484. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  485. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  486. last_two_bytes[0] = self.nb.i2c.dr.read().dr().bits();
  487. self.nb.send_stop();
  488. last_two_bytes[1] = self.nb.i2c.dr.read().dr().bits();
  489. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  490. last_two_bytes[2] = self.nb.i2c.dr.read().dr().bits();
  491. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  492. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  493. }
  494. }
  495. Ok(())
  496. }
  497. }
  498. impl<I2C, PINS> WriteRead for BlockingI2c<I2C, PINS>
  499. where
  500. I2C: Deref<Target = I2cRegisterBlock>,
  501. {
  502. type Error = NbError<Error>;
  503. fn write_read(&mut self, addr: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> {
  504. if !bytes.is_empty() {
  505. self.write_without_stop(addr, bytes)?;
  506. }
  507. if !buffer.is_empty() {
  508. self.read(addr, buffer)?;
  509. } else if !bytes.is_empty() {
  510. self.nb.send_stop();
  511. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  512. }
  513. Ok(())
  514. }
  515. }