基于stm32f1的内部读写flash
作者:互联网
flash是存储芯片的一种,通过特定的程序可以修改里面的数据。FLASH在电子以及半导体领域内往往表示Flash Memory的意思,即平时所说的“闪存”,全名叫Flash EEPROM Memory。
它结合了ROM和RAM的长处,不仅具备电子可擦除可编程(EEPROM)的性能,还可以快速读取数据(NVRAM的优势),使数据不会因为断电而丢失。(来源于百度百科)
那么如何在单片机上进行内部flash的读写操作。主要分为以下几个步骤:
1.调用 HAL_FLASH_Unlock 解锁;
2.配置 FLASH_EraseInitTypeDef 擦除 flash 初始化结构体;
3.调用HAL_FLASHEx_Erase(&flash, &PageError)擦除页;
4.调用 HAL_FLASH_Program 函数写入数据;
5.调用 HAL_FLASH_Lock 上锁;
附上代码
#include "flash.h"
uint32_t startAddress;
uint32_t endAddress;
uint32_t STMFLASH_ReadWord(uint32_t faddr)
{
return *(__IO uint32_t*)(faddr);
}
//FLASH写入数据
void WriteFlash(uint32_t Address, uint32_t *Data,uint32_t Num)
{
uint16_t i = 0;
// Data = 12354678;
startAddress = SN;
endAddress = SN+16;
HAL_FLASH_Unlock();//1.解锁
FLASH_EraseInitTypeDef flash;
flash.TypeErase = FLASH_TYPEERASE_PAGES;
flash.PageAddress = Address;
flash.NbPages = 1;
uint32_t PageError = 0;
HAL_FLASHEx_Erase(&flash, &PageError);//2.擦除页
//在startAddress~endAddress写入4组0x12345678
while(startAddress < endAddress)
{
if(HAL_FLASH_Program(TYPEPROGRAM_WORD, startAddress, *Data) == HAL_OK)//3.写数据
{
startAddress +=4;
Data++;
}
}
//4、锁住FLASH
HAL_FLASH_Lock();
}
//FLASH读取数据
uint32_t ReadFlash(uint32_t Address,uint32_t *Data,uint32_t Num)
{
uint32_t i;
for(i=0;i<Num;i++)
{
Data[i]=STMFLASH_ReadWord(Address);//读取4个字节.
Address+=4;//偏移4个字节.
}
}
#ifndef __FLASH_H
#define __FLASH_H
#include "stm32f1xx_hal.h"
#define SN 0x08010000
#define PN 0x08010010
#define SOFTWARE_VERSION 0x08010020
#define HARDWARE_VERSION 0x08010030
uint32_t STMFLASH_ReadWord(uint32_t faddr);
void WriteFlash(uint32_t Address, uint32_t *Data,uint32_t Num);
uint32_t ReadFlash(uint32_t Address,uint32_t *Data,uint32_t Num);
#endif
调试验证的时候,可以定于两个数组,一个存放数据,一个读取数据
WriteFlash(SN,(uint32_t *)Pwd3,2);
ReadFlash(SN,(uint32_t *)test,2); //读取
将读出的数据在串口打印出来
printf(“pwd3=%s/n”,test);
可见与写入的数据是一样的,内部flash读写成功!
标签:FLASH,HAL,读写,flash,uint32,startAddress,Data,stm32f1 来源: https://blog.csdn.net/qq_52207268/article/details/122848393