Skip to content

Commit 94a9983

Browse files
committed
Add simple FLASH API
1 parent 1330097 commit 94a9983

File tree

4 files changed

+402
-0
lines changed

4 files changed

+402
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ required-features = ["rt"]
111111
name = "button_irq_rtfm"
112112
required-features = ["rt"]
113113

114+
[[example]]
115+
name = "flash"
116+
required-features = ["rt","stm32l082"]
117+
114118
[[example]]
115119
name = "i2c_dma"
116120
required-features = ["rt","stm32l0x2"]

examples/flash.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#![no_main]
2+
#![no_std]
3+
4+
5+
extern crate panic_semihosting;
6+
7+
8+
use cortex_m_rt::entry;
9+
use stm32l0xx_hal::{
10+
prelude::*,
11+
flash::{
12+
FLASH,
13+
FLASH_START,
14+
flash_size_in_kb,
15+
},
16+
pac,
17+
rcc,
18+
};
19+
20+
21+
#[entry]
22+
fn main() -> ! {
23+
let cp = cortex_m::Peripherals::take().unwrap();
24+
let dp = pac::Peripherals::take().unwrap();
25+
26+
let mut rcc = dp.RCC.freeze(rcc::Config::hsi16());
27+
let mut flash = FLASH::new(dp.FLASH, &mut rcc);
28+
let gpiob = dp.GPIOB.split(&mut rcc);
29+
30+
let mut led = gpiob.pb2.into_push_pull_output();
31+
32+
// Get the delay provider.
33+
let mut delay = cp.SYST.delay(rcc.clocks);
34+
35+
// This should be the first word in the second flash bank. Since this
36+
// example should be quite small, we can be reasonably sure that it fully
37+
// fits into the first flash bank. This means we won't overwrite our own
38+
// code or stall execution.
39+
//
40+
// This example requires STM32L082, which has 2 banks.
41+
let address = FLASH_START + flash_size_in_kb() / 2 * 1024;
42+
let address = address as *mut u32;
43+
44+
flash.erase_flash_page(address)
45+
.expect("Failed to erase Flash page (1)");
46+
for i in 0 .. 32 {
47+
let word = unsafe { *address.offset(i * 4) };
48+
assert_eq!(word, 0);
49+
}
50+
51+
flash.write_word(address, 0x12345678)
52+
.expect("Failed to write word");
53+
assert_eq!(unsafe { *address }, 0x12345678);
54+
55+
flash.erase_flash_page(address)
56+
.expect("Failed to erase Flash page (2)");
57+
for i in 0 .. 32 {
58+
let word = unsafe { *address.offset(i * 4) };
59+
assert_eq!(word, 0);
60+
}
61+
62+
// Blink LED to indicate we haven't panicked.
63+
loop {
64+
led.set_high().unwrap();
65+
delay.delay_ms(500_u16);
66+
67+
led.set_low().unwrap();
68+
delay.delay_ms(500_u16);
69+
}
70+
}

0 commit comments

Comments
 (0)