stm32f407 hal库读写flash
时间: 2025-07-11 07:51:34 浏览: 4
### STM32F407 HAL库 Flash读写教程
#### 1. 硬件与软件环境概述
STM32F407 是一款高性能微控制器,其内部集成了大容量的闪存存储器 (Flash)。为了实现对 Flash 的高效管理,STMicroelectronics 提供了 HAL 库作为开发工具的一部分。该库简化了底层驱动程序的设计过程,并提供了统一的应用接口。
对于 STM32F4 系列而言,使用 HAL 库可以方便地完成 Flash 的擦除、编程以及锁定等功能[^2]。需要注意的是,不同型号之间的具体实现可能有所差异,因此开发者应仔细查阅对应的数据手册和技术文档。
#### 2. 初始化配置
在开始任何实际的操作之前,必须先通过 STM32CubeMX 工具设置好项目参数并生成初始化代码框架。这一步骤包括但不限于定义时钟源频率、使能相关外设供电轨等基本准备工作。此外还需确认目标设备所支持的最大工作电压范围是否满足当前应用场景需求[^3]。
#### 3. 主要函数说明
以下是几个常用的 HAL 函数用于控制 Flash:
- **`HAL_FLASH_Unlock()`**: 解锁 Flash 访问权限以便后续执行修改命令。
- **`HAL_StatusTypeDef HAL_FLASH_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError)`**: 执行扇区或者页面级别的清除动作前需调用此API指定待处理区域位置及其大小信息;同时它还接受一个指向错误页码变量指针用来报告失败情况下的确切地址偏移量值。
- **`HAL_FLASH_Program(uint32_t TypeProgram,uint32_t Address,uint32_t Data)`**: 向给定的目标内存单元写入单字节/半字/全字形式的新数值。这里要注意不同类型处理器架构下数据宽度可能会有所不同,请参照官方资料选取合适的枚举常量传参进去。
- **`HAL_FLASH_Lock(void)`**: 当所有必要的变更完成后应当立即再次加锁保护起来防止意外篡改行为发生。
以上这些核心功能模块共同构成了整个流程链路图如下所示:
```plaintext
+-------------------+
| Unlock FLASH |
+-------------------+
↓
+-------------------+
| Erase Sector/Page |
+-------------------+
↓
+-------------------+
| Program Data |
+-------------------+
↓
+-------------------+
| Lock FLASH |
+-------------------+
```
#### 4. 示例代码展示
下面给出一段完整的 C 语言示范片段来演示如何利用上述提到的方法组合在一起达成预期效果——即向特定位置处填充自定义内容字符串"HelloWorld!" :
```c
#include "stm32f4xx_hal.h"
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
int main(void){
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
/* Step1: Unlock the flash program memory */
HAL_FLASH_Unlock();
/* Define variables needed by erase and write operations*/
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PAGEError=0;
/* Configure parameters required for erasing operation */
EraseInitStruct.TypeErase = TYPEERASE_PAGES; // Choose page level deletion mode here.
EraseInitStruct.PageAddress = ADDR_USER_PAGE;// Set starting point of area to be cleared as user defined space start address.
EraseInitStruct.NbPages = NUMBER_OF_PAGES_TO_BE_ERASED ;// Specify total number of consecutive pages involved.
if(HAL_OK != HAL_FLASHEx_Erase(&EraseInitStruct,&PAGEError)){
Error_Handler();/* Handle possible exceptions during this stage.*/
}
const char* str="HelloWorld!";
uint8_t i=0;
while(*str!='\0'){
if(HAL_OK!= HAL_FLASH_Program(TYPEPROGRAM_BYTE,(uint32_t)(ADDR_USER_PAGE+i),*(unsigned int*)str)){
Error_Handler();/* Deal with potential issues when writing individual bytes into designated spots within erased zone.*/
}
++i;
++str;
}
/* Finally re-lock access rights after finishing all intended modifications on non-volatile storage medium.*/
HAL_FLASH_Lock();
while (1){} // Infinite loop where application specific tasks could reside later stages development phase.
}
/**
* @brief This function handles errors encountered throughout execution lifetime cycle .
*/
__weak void Error_Handler(void){
// Implement your own error handling strategy inside this stubbed out placeholder routine body block structure definition section below...
}
```
---
####
阅读全文
相关推荐


















