|
4 | 4 | use panic_halt as _;
|
5 | 5 | use stm32f0xx_hal as hal;
|
6 | 6 |
|
7 |
| -use crate::hal::{flash::FlashExt, pac, prelude::*}; |
| 7 | +use crate::hal::{ |
| 8 | + flash::{FlashExt, LockedFlash}, |
| 9 | + pac, |
| 10 | + prelude::*, |
| 11 | +}; |
8 | 12 |
|
9 | 13 | use cortex_m_rt::entry;
|
10 |
| -use embedded_storage::nor_flash::NorFlash; |
| 14 | +use embedded_storage::nor_flash::{NorFlash, ReadNorFlash}; |
11 | 15 |
|
12 | 16 | #[entry]
|
13 | 17 | fn main() -> ! {
|
14 | 18 | if let Some(mut p) = pac::Peripherals::take() {
|
15 | 19 | let _ = p.RCC.configure().freeze(&mut p.FLASH);
|
16 | 20 |
|
17 | 21 | // 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; |
19 | 23 | const OFFSET_END: u32 = OFFSET_START + 1024;
|
20 | 24 | // Unlock flash before writing
|
21 | 25 | let mut unlocked_flash = p.FLASH.unlocked();
|
22 | 26 |
|
23 | 27 | NorFlash::erase(&mut unlocked_flash, OFFSET_START, OFFSET_END).unwrap();
|
24 |
| - NorFlash::erase(&mut unlocked_flash, 0x10000, 0x10000 + 1024).unwrap(); |
25 | 28 |
|
26 | 29 | // Write some data to the start of that page
|
27 | 30 | let write_data = [0xC0_u8, 0xFF_u8, 0xEE_u8, 0x00_u8];
|
28 | 31 | match NorFlash::write(&mut unlocked_flash, OFFSET_START, &write_data) {
|
29 |
| - Err(e) => { |
30 |
| - let err = e; |
31 |
| - loop {} |
32 |
| - } |
| 32 | + Err(_) => panic!(), |
33 | 33 | Ok(_) => (),
|
34 | 34 | }
|
35 | 35 |
|
| 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 | + |
36 | 41 | // Lock flash by dropping it
|
37 | 42 | drop(unlocked_flash);
|
38 | 43 |
|
39 |
| - // Read back the slice from flash |
| 44 | + // It is also possible to read "manually" using core functions |
40 | 45 | let read_data = unsafe {
|
41 | 46 | 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, |
43 | 48 | write_data.len(),
|
44 | 49 | )
|
45 | 50 | };
|
| 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(); |
46 | 60 |
|
47 |
| - assert_eq!(write_data, *read_data); |
| 61 | + assert_eq!(write_data, read_buffer); |
48 | 62 | }
|
49 | 63 | loop {
|
50 | 64 | continue;
|
|
0 commit comments