如何在STM32F4,Cortex M4上写入/读取FLASH [英] How to write/read to FLASH on STM32F4, Cortex M4

查看:734
本文介绍了如何在STM32F4,Cortex M4上写入/读取FLASH的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向FLASH中写入一个变量,例如一个数字为5的整数,然后在断电并重新打开设备电源后再读取它.

I want to write a variable, for example an integer with the number 5 to the FLASH and then after the power goes away and the device is turned on again read it.

我已经知道,要写东西,我首先需要擦除页面然后再写.

I already know that in order to write something I first need to erase the page and then write.

在手册中说:

In the manual it says:

  1. 在Flash选项密钥寄存器(FLASH_OPTKEYR)中写入OPTKEY1 = 0x0819 2A3B
  2. 在Flash选项密钥寄存器(FLASH_OPTKEYR)中写入OPTKEY2 = 0x4C5D 6E7F

我如何执行此任务?

扇区0的块地址从0x0800 0000到0x0800 3FFF,这是我要写入的位置.

Sector 0 has a Block adress from 0x0800 0000 to 0x0800 3FFF, this is where I want to write.

此处是指向手册的链接,第71页:

Here the link to the manual, page 71: STM32 Manual

推荐答案

您可以使用以下代码通过HAL库将数据写入Flash.

You can use following code for write data to flash with HAL library.

void Write_Flash(uint8_t data)
{
     HAL_FLASH_Unlock();
     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGSERR );
     FLASH_Erase_Sector(FLASH_SECTOR_6, VOLTAGE_RANGE_3);
     HAL_FLASH_Program(TYPEPROGRAM_WORD, FlashAddress, data);
     HAL_FLASH_Lock();
}

您应按以下方式更新链接描述文件.在MEMORY中添加DATA并在SECTIONS中添加.user_data.

You should update linker script as follows. Add DATA in MEMORY and add .user_data in SECTIONS.

MEMORY
{
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 320K
CCMRAM (rw)      : ORIGIN = 0x10000000, LENGTH = 64K
FLASH (rx)      : ORIGIN = 0x8000000, LENGTH = 2048K
DATA (rwx)      : ORIGIN = 0x08040000, LENGTH = 128k
}

/* Define output sections */
SECTIONS
{
 .user_data :
  {
    . = ALIGN(4);
     KEEP(*(.user_data))
    . = ALIGN(4);
  } > DATA

您应该在主代码上添加以下属性,以便在开机后读取数据

You should add following attribute on main code for reading data after power on

__attribute__((__section__(".user_data"))) const char userConfig[64];

完成所有这些操作后,您可以通过调用userConfig[0]读取Flash数据.

After all these, you can read your flash data with calling userConfig[0].

这篇关于如何在STM32F4,Cortex M4上写入/读取FLASH的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆