Skip to content

Commit b492dc4

Browse files
Piroro-hsSh3Rm4n
authored andcommitted
Fix I2C clock source
1 parent 969d634 commit b492dc4

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/i2c.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use core::convert::TryFrom;
55
use crate::{
66
gpio::{gpioa, gpiob, gpiof, AF4},
77
hal::blocking::i2c::{Read, Write, WriteRead},
8-
pac::{I2C1, I2C2},
8+
pac::{I2C1, I2C2, RCC, rcc::cfgr3::I2C1SW_A},
99
rcc::{Clocks, APB1},
1010
time::Hertz,
1111
};
@@ -83,7 +83,7 @@ macro_rules! busy_wait {
8383
}
8484

8585
macro_rules! hal {
86-
($($I2CX:ident: ($i2cX:ident, $i2cXen:ident, $i2cXrst:ident),)+) => {
86+
($($I2CX:ident: ($i2cX:ident, $i2cXen:ident, $i2cXrst:ident, $i2cXsw:ident),)+) => {
8787
$(
8888
impl<SCL, SDA> I2c<$I2CX, (SCL, SDA)> {
8989
/// Configures the I2C peripheral to work in master mode
@@ -106,6 +106,12 @@ macro_rules! hal {
106106

107107
assert!(freq <= 1_000_000);
108108

109+
// NOTE(unsafe) atomic read with no side effects
110+
let i2cclk = match unsafe { (*RCC::ptr()).cfgr3.read().$i2cXsw().variant() } {
111+
I2C1SW_A::HSI => 8_000_000,
112+
I2C1SW_A::SYSCLK => clocks.sysclk().0,
113+
};
114+
109115
// TODO review compliance with the timing requirements of I2C
110116
// t_I2CCLK = 1 / PCLK1
111117
// t_PRESC = (PRESC + 1) * t_I2CCLK
@@ -114,7 +120,6 @@ macro_rules! hal {
114120
//
115121
// t_SYNC1 + t_SYNC2 > 4 * t_I2CCLK
116122
// t_SCL ~= t_SYNC1 + t_SYNC2 + t_SCLL + t_SCLH
117-
let i2cclk = clocks.pclk1().0;
118123
let ratio = i2cclk / freq - 4;
119124
let (presc, scll, sclh, sdadel, scldel) = if freq >= 100_000 {
120125
// fast-mode or fast-mode plus
@@ -427,11 +432,11 @@ macro_rules! hal {
427432
feature = "stm32f398",
428433
))]
429434
hal! {
430-
I2C1: (i2c1, i2c1en, i2c1rst),
431-
I2C2: (i2c2, i2c2en, i2c2rst),
435+
I2C1: (i2c1, i2c1en, i2c1rst, i2c1sw),
436+
I2C2: (i2c2, i2c2en, i2c2rst, i2c2sw),
432437
}
433438

434439
#[cfg(feature = "stm32f334")]
435440
hal! {
436-
I2C1: (i2c1, i2c1en, i2c1rst),
441+
I2C1: (i2c1, i2c1en, i2c1rst, i2c1sw),
437442
}

0 commit comments

Comments
 (0)