flash.h
#ifndef _FLASH_H_
#define _FLASH_H_
#include "stm32f10x_flash.h"
#define StartServerManageFlashAddress ((u32)0x0801FC00)
#define SECTOR_SIZE 1024
#define FLASH_SIZE 128
void FLASH_WriteMoreData(uint32_t startAddress,uint16_t *writeData,uint16_t countToWrite);
uint16_t FLASH_ReadHalfWord(uint32_t address);
void FLASH_ReadMoreData(uint32_t startAddress,uint16_t *readData,uint16_t countToRead);
void write_to_flash(u16 *buff, u16 count_len);
void read_from_flash(u16 *buff, u16 count_len);
#endif
flash.c
#include "flash.h"
//从指定地址开始写入多个数据
void FLASH_WriteMoreData(uint32_t startAddress,uint16_t *writeData,uint16_t countToWrite)
{
uint32_t offsetAddress=startAddress - FLASH_BASE;
uint32_t sectorPosition=offsetAddress/SECTOR_SIZE;
uint32_t sectorStartAddress=sectorPosition*SECTOR_SIZE+FLASH_BASE;
uint16_t dataIndex;
if(startAddress<FLASH_BASE||((startAddress+countToWrite*2)>=(FLASH_BASE + SECTOR_SIZE * FLASH_SIZE)))
{
return;//非法地址
}
FLASH_Unlock(); //解锁写保护
FLASH_ErasePage(sectorStartAddress);//擦除这个扇区
for(dataIndex=0;dataIndex<countToWrite;dataIndex++)
{
FLASH_ProgramHalfWord(startAddress+dataIndex*2,writeData[dataIndex]);
}
FLASH_Lock();//上锁写保护
}
//读取指定地址的半字(16位数据)
uint16_t FLASH_ReadHalfWord(uint32_t address)
{
return *(__IO uint16_t*)address;
}
//从指定地址开始读取多个数据
void FLASH_ReadMoreData(uint32_t startAddress,uint16_t *readData,uint16_t countToRead)
{
uint16_t dataIndex;
for(dataIndex=0;dataIndex<countToRead;dataIndex++)
{
readData[dataIndex]=FLASH_ReadHalfWord(startAddress+dataIndex*2);
}
}
void write_to_flash(u16 *buff,u16 count_len)
{
//u16 buff[1200];
//u16 count_len = 2272 / 2;
FLASH_WriteMoreData(StartServerManageFlashAddress,buff,count_len);
}
void read_from_flash(u16 *buff,u16 count_len)
{
//u16 buff[1200];
//u16 count_len = 2272 / 2;
FLASH_ReadMoreData(StartServerManageFlashAddress,buff,count_len);
}
使用的话就是直接使用wirte_to_flash来写或者是read_to_flash来读,亲测有效。
这篇博客里的代码是参考其他博主的,但是由于我后面没记录下博主的网址,所以就没注明,若是原创博主麻烦可以跟我私信,后面我会加上来自哪里的,感谢。