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);
}
If you use it, you can directly use wirte_to_flash to write or read_to_flash to read, and the test is effective.
The code in this blog is based on other bloggers, but since I didn’t record the blogger’s URL later, I didn’t specify it. If the original blogger troubles you, you can send me a private message. I will add where I came from later. thank.