Skip to content

Commit 280d591

Browse files
committed
Add I2C scanner example
Inspired from https://github.com/stm32-rs/stm32f3xx-hal/blob/master/examples/i2c_scanner.rs Signed-off-by: Moritz Scheuren <[email protected]>
1 parent 708ac86 commit 280d591

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

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+
4+
#![no_std]
5+
#![no_main]
6+
7+
use core::ops::Range;
8+
9+
use panic_semihosting as _;
10+
11+
use cortex_m_rt::entry;
12+
use cortex_m_semihosting::{hprint, hprintln};
13+
14+
use stm32f7xx_hal::{self as hal, gpio::GpioExt, pac, prelude::*};
15+
16+
const VALID_ADDR_RANGE: Range<u8> = 0x08..0x78;
17+
18+
#[entry]
19+
fn main() -> ! {
20+
let dp = pac::Peripherals::take().unwrap();
21+
22+
let mut rcc = dp.RCC.constrain();
23+
let clocks = rcc.cfgr.freeze();
24+
25+
let gpiob = dp.GPIOB.split();
26+
27+
// Configure I2C1
28+
let scl = gpiob.pb8.into_alternate_open_drain::<4>();
29+
let sda = gpiob.pb7.into_alternate_open_drain::<4>();
30+
let mut i2c = hal::i2c::BlockingI2c::i2c1(
31+
dp.I2C1,
32+
(scl, sda),
33+
hal::i2c::Mode::fast(100_000.Hz()),
34+
clocks,
35+
&mut rcc.apb1,
36+
50_000,
37+
);
38+
39+
hprintln!("Start i2c scanning...").expect("Error using hprintln.");
40+
hprintln!().unwrap();
41+
42+
for addr in 0x00_u8..0x80 {
43+
// Write the empty array and check the slave response.
44+
let byte: [u8; 1] = [0; 1];
45+
if VALID_ADDR_RANGE.contains(&addr) && i2c.write(addr, &byte).is_ok() {
46+
hprint!("{:02x}", addr).unwrap();
47+
} else {
48+
hprint!("..").unwrap();
49+
}
50+
if addr % 0x10 == 0x0F {
51+
hprintln!().unwrap();
52+
} else {
53+
hprint!(" ").unwrap();
54+
}
55+
}
56+
57+
hprintln!().unwrap();
58+
hprintln!("Done!").unwrap();
59+
60+
loop {}
61+
}

0 commit comments

Comments
 (0)