Skip to content

Commit c86ea9f

Browse files
committed
Clean up flash read write example
1 parent 5524712 commit c86ea9f

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

examples/flash_read_write.rs

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,47 +4,61 @@
44
use panic_halt as _;
55
use stm32f0xx_hal as hal;
66

7-
use crate::hal::{flash::FlashExt, pac, prelude::*};
7+
use crate::hal::{
8+
flash::{FlashExt, LockedFlash},
9+
pac,
10+
prelude::*,
11+
};
812

913
use cortex_m_rt::entry;
10-
use embedded_storage::nor_flash::NorFlash;
14+
use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
1115

1216
#[entry]
1317
fn main() -> ! {
1418
if let Some(mut p) = pac::Peripherals::take() {
1519
let _ = p.RCC.configure().freeze(&mut p.FLASH);
1620

1721
// All examples use the first 16K of flash for the program so we use the first page after that
18-
const OFFSET_START: u32 = 32 * 1024;
22+
const OFFSET_START: u32 = 16 * 1024;
1923
const OFFSET_END: u32 = OFFSET_START + 1024;
2024
// Unlock flash before writing
2125
let mut unlocked_flash = p.FLASH.unlocked();
2226

2327
NorFlash::erase(&mut unlocked_flash, OFFSET_START, OFFSET_END).unwrap();
24-
NorFlash::erase(&mut unlocked_flash, 0x10000, 0x10000 + 1024).unwrap();
2528

2629
// Write some data to the start of that page
2730
let write_data = [0xC0_u8, 0xFF_u8, 0xEE_u8, 0x00_u8];
2831
match NorFlash::write(&mut unlocked_flash, OFFSET_START, &write_data) {
29-
Err(e) => {
30-
let err = e;
31-
loop {}
32-
}
32+
Err(_) => panic!(),
3333
Ok(_) => (),
3434
}
3535

36+
// Read back the written data from flash
37+
let mut read_buffer: [u8; 4] = [0; 4];
38+
unlocked_flash.read(OFFSET_START, &mut read_buffer).unwrap();
39+
assert_eq!(write_data, read_buffer);
40+
3641
// Lock flash by dropping it
3742
drop(unlocked_flash);
3843

39-
// Read back the slice from flash
44+
// It is also possible to read "manually" using core functions
4045
let read_data = unsafe {
4146
core::slice::from_raw_parts(
42-
(p.FLASH.address() + 16 * 1024) as *const u8,
47+
(p.FLASH.address() + OFFSET_START as usize) as *const u8,
4348
write_data.len(),
4449
)
4550
};
51+
for (i, d) in read_data.iter().enumerate() {
52+
read_buffer[i] = *d;
53+
}
54+
55+
assert_eq!(write_data, read_buffer);
56+
57+
// Reading is also possible on locked flash
58+
let mut locked_flash = LockedFlash::new(p.FLASH);
59+
locked_flash.read(OFFSET_START, &mut read_buffer).unwrap();
4660

47-
assert_eq!(write_data, *read_data);
61+
assert_eq!(write_data, read_buffer);
4862
}
4963
loop {
5064
continue;

0 commit comments

Comments
 (0)