diff --git a/embassy-stm32/src/flash/f4.rs b/embassy-stm32/src/flash/f4.rs index f6dc7e95..ad71f145 100644 --- a/embassy-stm32/src/flash/f4.rs +++ b/embassy-stm32/src/flash/f4.rs @@ -99,9 +99,9 @@ unsafe fn get_sector(addr: u32) -> u8 { pub(crate) unsafe fn blocking_erase(from: u32, to: u32) -> Result<(), Error> { let start_sector = get_sector(from); - let end_sector = get_sector(to); + let end_sector = get_sector(to - 1); // end range is exclusive - for sector in start_sector..end_sector { + for sector in start_sector..=end_sector { let ret = erase_sector(sector as u8); if ret.is_err() { return ret; @@ -115,6 +115,8 @@ unsafe fn erase_sector(sector: u8) -> Result<(), Error> { let bank = sector / SECOND_BANK_SECTOR_START as u8; let snb = (bank << 4) + (sector % SECOND_BANK_SECTOR_START as u8); + trace!("Erasing sector: {}", sector); + pac::FLASH.cr().modify(|w| { w.set_ser(true); w.set_snb(snb) diff --git a/examples/stm32f4/src/bin/flash.rs b/examples/stm32f4/src/bin/flash.rs index b531d6f1..ad45df82 100644 --- a/examples/stm32f4/src/bin/flash.rs +++ b/examples/stm32f4/src/bin/flash.rs @@ -7,36 +7,46 @@ use embassy::executor::Spawner; use embassy::time::{Duration, Timer}; use embassy_stm32::flash::Flash; use embassy_stm32::Peripherals; -use embedded_storage::nor_flash::{NorFlash, ReadNorFlash}; use {defmt_rtt as _, panic_probe as _}; #[embassy::main] async fn main(_spawner: Spawner, p: Peripherals) { info!("Hello Flash!"); - const ADDR: u32 = 0x10_0000; - - // wait a bit before accessing the flash - Timer::after(Duration::from_millis(300)).await; - let mut f = Flash::unlock(p.FLASH); + // Sector 5 + test_flash(&mut f, 128 * 1024, 128 * 1024); + + // Sector 11, last in bank 1 + test_flash(&mut f, (1024 - 128) * 1024, 128 * 1024); + + // Sectors 12..=16, start of bank 2 (16K, 16K, 16K, 16K, 64K) + test_flash(&mut f, 1024 * 1024, 128 * 1024); + + // Sectors 23, last in bank 2 + test_flash(&mut f, (2048 - 128) * 1024, 128 * 1024); +} + +fn test_flash(f: &mut Flash, offset: u32, size: u32) { + info!("Testing offset: {=u32:#X}, size: {=u32:#X}", offset, size); + info!("Reading..."); let mut buf = [0u8; 32]; - unwrap!(f.read(ADDR, &mut buf)); + unwrap!(f.read(offset, &mut buf)); info!("Read: {=[u8]:x}", buf); info!("Erasing..."); - unwrap!(f.erase(ADDR, ADDR + 128 * 1024)); + unwrap!(f.erase(offset, offset + size)); info!("Reading..."); let mut buf = [0u8; 32]; - unwrap!(f.read(ADDR, &mut buf)); + unwrap!(f.read(offset, &mut buf)); info!("Read after erase: {=[u8]:x}", buf); info!("Writing..."); unwrap!(f.write( - ADDR, + offset, &[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 @@ -45,7 +55,7 @@ async fn main(_spawner: Spawner, p: Peripherals) { info!("Reading..."); let mut buf = [0u8; 32]; - unwrap!(f.read(ADDR, &mut buf)); + unwrap!(f.read(offset, &mut buf)); info!("Read: {=[u8]:x}", buf); assert_eq!( &buf[..],