Skip to content

Commit dee229c

Browse files
committed
Add I2C example
1 parent 1c8b14e commit dee229c

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,7 @@ required-features = ["stm32f303"]
134134
[[example]]
135135
name = "adc"
136136
required-features = ["stm32f303"]
137+
138+
[[example]]
139+
name = "i2c_scanner"
140+
required-features = ["stm32f303xc"]

examples/i2c_scanner.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//! Example of using I2C.
2+
//! Scans available I2C devices on bus and print the result.
3+
//! Appropriate pull-up registers should be installed on I2C bus.
4+
//! Target board: STM32F3DISCOVERY
5+
6+
#![no_std]
7+
#![no_main]
8+
9+
use core::ops::Range;
10+
11+
use panic_semihosting as _;
12+
13+
use cortex_m::asm;
14+
use cortex_m_rt::entry;
15+
use cortex_m_semihosting::{hprint, hprintln};
16+
17+
use stm32f3xx_hal::{self as hal, pac, prelude::*};
18+
19+
const VALID_ADDR_RANGE: Range<u8> = 0x08..0x78;
20+
21+
#[entry]
22+
fn main() -> ! {
23+
let dp = pac::Peripherals::take().unwrap();
24+
25+
let mut flash = dp.FLASH.constrain();
26+
let mut rcc = dp.RCC.constrain();
27+
let clocks = rcc.cfgr.freeze(&mut flash.acr);
28+
29+
let mut gpiob = dp.GPIOB.split(&mut rcc.ahb);
30+
31+
// Configure I2C1
32+
let pins = (
33+
gpiob.pb6.into_af4(&mut gpiob.moder, &mut gpiob.afrl), // SCL
34+
gpiob.pb7.into_af4(&mut gpiob.moder, &mut gpiob.afrl), // SDA
35+
);
36+
let mut i2c = hal::i2c::I2c::new(dp.I2C1, pins, 100.khz(), clocks, &mut rcc.apb1);
37+
38+
hprintln!("Start i2c scanning...").expect("Error using hprintln.");
39+
hprintln!().unwrap();
40+
41+
for addr in 0x00_u8..0x80 {
42+
// Write the empty array and check the slave response.
43+
if VALID_ADDR_RANGE.contains(&addr) && i2c.write(addr, &[]).is_ok() {
44+
hprint!("{:02x}", addr).unwrap();
45+
} else {
46+
hprint!("..").unwrap();
47+
}
48+
if addr % 0x10 == 0x0F {
49+
hprintln!().unwrap();
50+
} else {
51+
hprint!(" ").unwrap();
52+
}
53+
}
54+
55+
hprintln!().unwrap();
56+
hprintln!("Done!").unwrap();
57+
58+
loop {
59+
asm::wfi();
60+
}
61+
}

0 commit comments

Comments
 (0)