File tree Expand file tree Collapse file tree 2 files changed +70
-0
lines changed
Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Original file line number Diff line number Diff 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 ]
Original file line number Diff line number Diff line change 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 stm32f4xx_hal:: {
15+ self as hal,
16+ gpio:: GpioExt ,
17+ i2c:: { DutyCycle , I2c } ,
18+ pac,
19+ prelude:: * ,
20+ } ;
21+
22+ const VALID_ADDR_RANGE : Range < u8 > = 0x08 ..0x78 ;
23+
24+ #[ entry]
25+ fn main ( ) -> ! {
26+ let dp = pac:: Peripherals :: take ( ) . unwrap ( ) ;
27+
28+ let rcc = dp. RCC . constrain ( ) ;
29+ let clocks = rcc. cfgr . freeze ( ) ;
30+
31+ let gpiob = dp. GPIOB . split ( ) ;
32+
33+ // Configure I2C1
34+ let scl = gpiob. pb8 ;
35+ let sda = gpiob. pb7 ;
36+ let mut i2c = I2c :: new (
37+ dp. I2C1 ,
38+ ( scl, sda) ,
39+ hal:: i2c:: Mode :: standard ( 100_000 . Hz ( ) ) ,
40+ & clocks,
41+ ) ;
42+
43+ hprintln ! ( "Start i2c scanning..." ) ;
44+ hprintln ! ( ) ;
45+
46+ for addr in 0x00_u8 ..0x80 {
47+ // Write the empty array and check the slave response.
48+ let byte: [ u8 ; 1 ] = [ 0 ; 1 ] ;
49+ if VALID_ADDR_RANGE . contains ( & addr) && i2c. write ( addr, & byte) . is_ok ( ) {
50+ hprint ! ( "{:02x}" , addr) ;
51+ } else {
52+ hprint ! ( ".." ) ;
53+ }
54+ if addr % 0x10 == 0x0F {
55+ hprintln ! ( ) ;
56+ } else {
57+ hprint ! ( " " ) ;
58+ }
59+ }
60+
61+ hprintln ! ( ) ;
62+ hprintln ! ( "Done!" ) ;
63+
64+ #[ allow( clippy:: empty_loop) ]
65+ loop { }
66+ }
You can’t perform that action at this time.
0 commit comments