C语言 如何在 STM32F4、Cortex M4 上写入/读取 FLASH
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44443619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write/read to FLASH on STM32F4, Cortex M4
提问by Alex M.
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.
我想写一个变量,例如一个数字为 5 的整数到 FLASH,然后在电源消失并再次打开设备后读取它。
I already know that in order to write something I first need to erase the page and then write.
我已经知道,为了写东西,我首先需要擦除页面,然后再写。
In the manual it says:
在手册中它说:
- Write OPTKEY1 = 0x0819 2A3B in the Flash option key register (FLASH_OPTKEYR)
- Write OPTKEY2 = 0x4C5D 6E7F in the Flash option key register (FLASH_OPTKEYR)
- 将 OPTKEY1 = 0x0819 2A3B 写入 Flash 选项密钥寄存器(FLASH_OPTKEYR)
- 在 Flash 选项密钥寄存器(FLASH_OPTKEYR)中写入 OPTKEY2 = 0x4C5D 6E7F
How do I perform this tasks?
如何执行此任务?
Sector 0 has a Block adress from 0x0800 0000 to 0x0800 3FFF, this is where I want to write.
扇区 0 的块地址从 0x0800 0000 到 0x0800 3FFF,这就是我想写的地方。
Here the link to the manual, page 71: STM32 Manual
这里是手册的链接,第 71 页:STM32 手册
回答by Gürta? Kadem
You can use following code for write data to flash with HAL library.
您可以使用以下代码将数据写入带有 HAL 库的闪存。
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();
}
You should update linker script as follows. Add DATAin MEMORYand add .user_datain SECTIONS.
您应该按如下方式更新链接描述文件。添加DATA的MEMORY,添加.user_data的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];
After all these, you can read your flash data with calling userConfig[0].
完成所有这些之后,您可以通过调用读取您的闪存数据userConfig[0]。

![C语言 “%d”需要“int”类型的参数,但参数 2 的类型为“long unsigned int”[-Wformat=]](/res/img/loading.gif)