Skip to content

Commit da63ec4

Browse files
authored
Merge pull request #758 from stm32-rs/i2c-scanner
I2c scanner
2 parents e48b49d + 5101104 commit da63ec4

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- `i2c_scanner` example
13+
1014
### Changed
1115

1216
- Use `stm32f4-staging` until `stm32f4` is released [#706]

examples/i2c_scanner.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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 rtt_target::{rprint, rprintln, rtt_init_print};
10+
11+
use cortex_m_rt::entry;
12+
13+
use stm32f4xx_hal::{self as hal, gpio::GpioExt, i2c::I2c, pac, prelude::*};
14+
15+
const VALID_ADDR_RANGE: Range<u8> = 0x08..0x78;
16+
17+
#[entry]
18+
fn main() -> ! {
19+
rtt_init_print!();
20+
let dp = pac::Peripherals::take().unwrap();
21+
22+
let 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;
29+
let sda = gpiob.pb7;
30+
let mut i2c = I2c::new(
31+
dp.I2C1,
32+
(scl, sda),
33+
hal::i2c::Mode::standard(100.kHz()),
34+
&clocks,
35+
);
36+
37+
rprintln!("Start i2c scanning...");
38+
rprintln!();
39+
40+
for addr in 0x00_u8..0x80 {
41+
// Write the empty array and check the slave response.
42+
let byte: [u8; 1] = [0; 1];
43+
if VALID_ADDR_RANGE.contains(&addr) && i2c.write(addr, &byte).is_ok() {
44+
rprint!("{:02x}", addr);
45+
} else {
46+
rprint!("..");
47+
}
48+
if addr % 0x10 == 0x0F {
49+
rprintln!();
50+
} else {
51+
rprint!(" ");
52+
}
53+
}
54+
55+
rprintln!();
56+
rprintln!("Done!");
57+
58+
#[allow(clippy::empty_loop)]
59+
loop {}
60+
}
61+
62+
use core::panic::PanicInfo;
63+
#[inline(never)]
64+
#[panic_handler]
65+
fn panic(info: &PanicInfo) -> ! {
66+
rprintln!("{}", info);
67+
loop {} // You might need a compiler fence in here.
68+
}

0 commit comments

Comments
 (0)