i2c.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. Err(Other(Error::Bus))
  203. } else if sr1.arlo().bit_is_set() {
  204. Err(Other(Error::Arbitration))
  205. } else if sr1.af().bit_is_set() {
  206. Err(Other(Error::Acknowledge))
  207. } else if sr1.ovr().bit_is_set() {
  208. Err(Other(Error::Overrun))
  209. } else if sr1.$flag().bit_is_set() {
  210. Ok(())
  211. } else {
  212. Err(WouldBlock)
  213. }
  214. }};
  215. }
  216. macro_rules! busy_wait {
  217. ($nb_expr:expr, $exit_cond:expr) => {{
  218. loop {
  219. let res = $nb_expr;
  220. if res != Err(WouldBlock) {
  221. break res;
  222. }
  223. if $exit_cond {
  224. break res;
  225. }
  226. }
  227. }};
  228. }
  229. macro_rules! busy_wait_cycles {
  230. ($nb_expr:expr, $cycles:expr) => {{
  231. let started = DWT::get_cycle_count();
  232. let cycles = $cycles;
  233. busy_wait!(
  234. $nb_expr,
  235. DWT::get_cycle_count().wrapping_sub(started) >= cycles
  236. )
  237. }};
  238. }
  239. pub type I2cRegisterBlock = crate::pac::i2c1::RegisterBlock;
  240. impl<I2C, PINS> I2c<I2C, PINS>
  241. where
  242. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  243. I2C::Bus: GetBusFreq,
  244. {
  245. /// Configures the I2C peripheral to work in master mode
  246. fn _i2c(i2c: I2C, pins: PINS, mode: Mode, clocks: Clocks, apb: &mut I2C::Bus) -> Self {
  247. I2C::enable(apb);
  248. I2C::reset(apb);
  249. let pclk1 = I2C::Bus::get_frequency(&clocks).0;
  250. assert!(mode.get_frequency().0 <= 400_000);
  251. let mut i2c = I2c {
  252. i2c,
  253. pins,
  254. mode,
  255. pclk1,
  256. };
  257. i2c.init();
  258. i2c
  259. }
  260. }
  261. impl<I2C, PINS> I2c<I2C, PINS>
  262. where
  263. I2C: Deref<Target = I2cRegisterBlock>,
  264. {
  265. /// Initializes I2C. Configures the `I2C_TRISE`, `I2C_CRX`, and `I2C_CCR` registers
  266. /// according to the system frequency and I2C mode.
  267. fn init(&mut self) {
  268. let freq = self.mode.get_frequency();
  269. let pclk1_mhz = (self.pclk1 / 1000000) as u16;
  270. self.i2c
  271. .cr2
  272. .write(|w| unsafe { w.freq().bits(pclk1_mhz as u8) });
  273. self.i2c.cr1.write(|w| w.pe().clear_bit());
  274. match self.mode {
  275. Mode::Standard { .. } => {
  276. self.i2c
  277. .trise
  278. .write(|w| w.trise().bits((pclk1_mhz + 1) as u8));
  279. self.i2c.ccr.write(|w| unsafe {
  280. w.ccr().bits(((self.pclk1 / (freq.0 * 2)) as u16).max(4))
  281. });
  282. }
  283. Mode::Fast { ref duty_cycle, .. } => {
  284. self.i2c
  285. .trise
  286. .write(|w| w.trise().bits((pclk1_mhz * 300 / 1000 + 1) as u8));
  287. self.i2c.ccr.write(|w| {
  288. let (freq, duty) = match duty_cycle {
  289. &DutyCycle::Ratio2to1 => {
  290. (((self.pclk1 / (freq.0 * 3)) as u16).max(1), false)
  291. }
  292. &DutyCycle::Ratio16to9 => {
  293. (((self.pclk1 / (freq.0 * 25)) as u16).max(1), true)
  294. }
  295. };
  296. unsafe { w.ccr().bits(freq).duty().bit(duty).f_s().set_bit() }
  297. });
  298. }
  299. };
  300. self.i2c.cr1.modify(|_, w| w.pe().set_bit());
  301. }
  302. /// Perform an I2C software reset
  303. fn reset(&mut self) {
  304. self.i2c.cr1.write(|w| w.pe().set_bit().swrst().set_bit());
  305. self.i2c.cr1.reset();
  306. self.init();
  307. }
  308. /// Generate START condition
  309. fn send_start(&mut self) {
  310. self.i2c.cr1.modify(|_, w| w.start().set_bit());
  311. }
  312. /// Check if START condition is generated. If the condition is not generated, this
  313. /// method returns `WouldBlock` so the program can act accordingly
  314. /// (busy wait, async, ...)
  315. fn wait_after_sent_start(&mut self) -> NbResult<(), Error> {
  316. wait_for_flag!(self.i2c, sb)
  317. }
  318. /// Check if STOP condition is generated. If the condition is not generated, this
  319. /// method returns `WouldBlock` so the program can act accordingly
  320. /// (busy wait, async, ...)
  321. fn wait_for_stop(&mut self) -> NbResult<(), Error> {
  322. if self.i2c.cr1.read().stop().is_no_stop() {
  323. Ok(())
  324. } else {
  325. Err(WouldBlock)
  326. }
  327. }
  328. /// Sends the (7-Bit) address on the I2C bus. The 8th bit on the bus is set
  329. /// depending on wether it is a read or write transfer.
  330. fn send_addr(&self, addr: u8, read: bool) {
  331. self.i2c
  332. .dr
  333. .write(|w| w.dr().bits(addr << 1 | (if read { 1 } else { 0 })));
  334. }
  335. /// Generate STOP condition
  336. fn send_stop(&self) {
  337. self.i2c.cr1.modify(|_, w| w.stop().set_bit());
  338. }
  339. /// Releases the I2C peripheral and associated pins
  340. pub fn free(self) -> (I2C, PINS) {
  341. (self.i2c, self.pins)
  342. }
  343. }
  344. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  345. where
  346. I2C: Deref<Target = I2cRegisterBlock> + Enable + Reset,
  347. I2C::Bus: GetBusFreq,
  348. {
  349. fn _i2c(
  350. i2c: I2C,
  351. pins: PINS,
  352. mode: Mode,
  353. clocks: Clocks,
  354. apb: &mut I2C::Bus,
  355. start_timeout_us: u32,
  356. start_retries: u8,
  357. addr_timeout_us: u32,
  358. data_timeout_us: u32,
  359. ) -> Self {
  360. blocking_i2c(
  361. I2c::<I2C, _>::_i2c(i2c, pins, mode, clocks, apb),
  362. clocks,
  363. start_timeout_us,
  364. start_retries,
  365. addr_timeout_us,
  366. data_timeout_us,
  367. )
  368. }
  369. }
  370. impl<I2C, PINS> BlockingI2c<I2C, PINS>
  371. where
  372. I2C: Deref<Target = I2cRegisterBlock>,
  373. {
  374. fn send_start_and_wait(&mut self) -> NbResult<(), Error> {
  375. // 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
  376. // 2.14.4 Wrong behavior of I2C peripheral in master mode after a misplaced STOP
  377. let mut retries_left = self.start_retries;
  378. let mut last_ret: NbResult<(), Error> = Err(WouldBlock);
  379. while retries_left > 0 {
  380. self.nb.send_start();
  381. last_ret = busy_wait_cycles!(self.nb.wait_after_sent_start(), self.start_timeout);
  382. if let Err(_) = last_ret {
  383. self.nb.reset();
  384. } else {
  385. break;
  386. }
  387. retries_left -= 1;
  388. }
  389. last_ret
  390. }
  391. fn write_without_stop(&mut self, addr: u8, bytes: &[u8]) -> NbResult<(), Error> {
  392. self.send_start_and_wait()?;
  393. self.nb.i2c.sr1.read();
  394. self.nb.send_addr(addr, false);
  395. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, addr), self.addr_timeout)?;
  396. self.nb.i2c.sr1.read();
  397. self.nb.i2c.sr2.read();
  398. self.nb.i2c.dr.write(|w| w.dr().bits(bytes[0]));
  399. for byte in &bytes[1..] {
  400. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, tx_e), self.data_timeout)?;
  401. self.nb.i2c.dr.write(|w| w.dr().bits(*byte));
  402. }
  403. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  404. Ok(())
  405. }
  406. }
  407. impl<I2C, PINS> Write for BlockingI2c<I2C, PINS>
  408. where
  409. I2C: Deref<Target = I2cRegisterBlock>,
  410. {
  411. type Error = NbError<Error>;
  412. fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> {
  413. self.write_without_stop(addr, bytes)?;
  414. self.nb.send_stop();
  415. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  416. Ok(())
  417. }
  418. }
  419. impl<I2C, PINS> Read for BlockingI2c<I2C, PINS>
  420. where
  421. I2C: Deref<Target = I2cRegisterBlock>,
  422. {
  423. type Error = NbError<Error>;
  424. fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
  425. self.send_start_and_wait()?;
  426. self.nb.i2c.sr1.read();
  427. self.nb.send_addr(addr, true);
  428. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, addr), self.addr_timeout)?;
  429. match buffer.len() {
  430. 1 => {
  431. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  432. self.nb.i2c.sr1.read();
  433. self.nb.i2c.sr2.read();
  434. self.nb.send_stop();
  435. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  436. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  437. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  438. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  439. }
  440. 2 => {
  441. self.nb
  442. .i2c
  443. .cr1
  444. .modify(|_, w| w.pos().set_bit().ack().set_bit());
  445. self.nb.i2c.sr1.read();
  446. self.nb.i2c.sr2.read();
  447. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  448. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  449. self.nb.send_stop();
  450. buffer[0] = self.nb.i2c.dr.read().dr().bits();
  451. buffer[1] = self.nb.i2c.dr.read().dr().bits();
  452. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  453. self.nb
  454. .i2c
  455. .cr1
  456. .modify(|_, w| w.pos().clear_bit().ack().clear_bit());
  457. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  458. }
  459. buffer_len => {
  460. self.nb.i2c.sr1.read();
  461. self.nb.i2c.sr2.read();
  462. let (first_bytes, last_two_bytes) = buffer.split_at_mut(buffer_len - 3);
  463. for byte in first_bytes {
  464. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  465. *byte = self.nb.i2c.dr.read().dr().bits();
  466. }
  467. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, btf), self.data_timeout)?;
  468. self.nb.i2c.cr1.modify(|_, w| w.ack().clear_bit());
  469. last_two_bytes[0] = self.nb.i2c.dr.read().dr().bits();
  470. self.nb.send_stop();
  471. last_two_bytes[1] = self.nb.i2c.dr.read().dr().bits();
  472. busy_wait_cycles!(wait_for_flag!(self.nb.i2c, rx_ne), self.data_timeout)?;
  473. last_two_bytes[2] = self.nb.i2c.dr.read().dr().bits();
  474. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  475. self.nb.i2c.cr1.modify(|_, w| w.ack().set_bit());
  476. }
  477. }
  478. Ok(())
  479. }
  480. }
  481. impl<I2C, PINS> WriteRead for BlockingI2c<I2C, PINS>
  482. where
  483. I2C: Deref<Target = I2cRegisterBlock>,
  484. {
  485. type Error = NbError<Error>;
  486. fn write_read(&mut self, addr: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> {
  487. if !bytes.is_empty() {
  488. self.write_without_stop(addr, bytes)?;
  489. }
  490. if !buffer.is_empty() {
  491. self.read(addr, buffer)?;
  492. } else if !bytes.is_empty() {
  493. self.nb.send_stop();
  494. busy_wait_cycles!(self.nb.wait_for_stop(), self.data_timeout)?;
  495. }
  496. Ok(())
  497. }
  498. }