Fix writing to last sector of F4 flash

This commit is contained in:
chemicstry 2022-07-14 19:41:39 +03:00
parent e4cacc3bb8
commit 039acda3a8
2 changed files with 25 additions and 13 deletions

View File

@ -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)

View File

@ -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[..],