STM32F10X--->BSP(FLASH)

Falsh擦除和写入

注意:FALSH 只有擦除后才能写入。

//BSP_FLASH.H

 

#ifndef __INTERNAL_FLASH_H
#define    __INTERNAL_FLASH_H

#include "stm32f10x.h"

/* STM32大容量产品每页大小2KByte,中、小容量产品每页大小1KByte */
#if defined (STM32F10X_HD) || defined (STM32F10X_HD_VL) || defined (STM32F10X_CL) || defined (STM32F10X_XL)
  #define FLASH_PAGE_SIZE    ((uint16_t)0x800)    //2048
#else
  #define FLASH_PAGE_SIZE    ((uint16_t)0x400)    //1024
#endif

//写入的起始地址与结束地址
#define WRITE_START_ADDR  ((uint32_t)0x08008000)
#define WRITE_END_ADDR    ((uint32_t)0x0800C000)
#define  WRITE_START_ADDR1  ((uint32_t)0x08008004)



typedef enum 
{
    FAILED = 0, 
  PASSED = !FAILED
} TestStatus;


int InternalFlash_Test(void);



#endif /* __INTERNAL_FLASH_H */

 

//BSP_flash.c

/**
  * @brief  InternalFlash_Test,对内部FLASH进行读写测试
  * @param  None
  * @retval None
  */
int InternalFlash_Test(void)
{
    uint32_t EraseCounter = 0x00;     //记录要擦除多少页
    uint32_t Address = 0x00;                //记录写入的地址
    uint32_t Data = 0x3210ABCD;            //记录写入的数据 
  uint32_t Data1 = 0x3210ABCF;            //记录写入的数据    
    uint32_t NbrOfPage = 0x00;            //记录写入多少页
    
    FLASH_Status FLASHStatus = FLASH_COMPLETE; //记录每次擦除的结果    
    TestStatus MemoryProgramStatus = PASSED;//记录整个测试结果
    

  /* 解锁 */
  FLASH_Unlock();

  /* 计算要擦除多少页 */
  NbrOfPage = (WRITE_END_ADDR - WRITE_START_ADDR) / FLASH_PAGE_SIZE;

  /* 清空所有标志位 */
  FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);    

  /* 按页擦除*/
  for(EraseCounter = 0; (EraseCounter < NbrOfPage) && (FLASHStatus == FLASH_COMPLETE); EraseCounter++)
  {
    FLASHStatus = FLASH_ErasePage(WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter));
  
    }
  
  /* 向内部FLASH写入数据 */
  Address = WRITE_START_ADDR;

  while((Address < WRITE_END_ADDR) && (FLASHStatus == FLASH_COMPLETE))
  {
    FLASHStatus = FLASH_ProgramWord(Address, Data);
    Address = Address + 4;    //地址偏移4个字节
  }
    
     /* 计算要擦除多少页 */
  NbrOfPage = (WRITE_END_ADDR - WRITE_START_ADDR) / FLASH_PAGE_SIZE;

  /* 清空所有标志位 */
  FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);    

  /* 按页擦除*/
  for(EraseCounter = 0; (EraseCounter < NbrOfPage) && (FLASHStatus == FLASH_COMPLETE); EraseCounter++)
  {
    FLASHStatus = FLASH_ErasePage(WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter));
  
    }
    
    
    
    //再次写入数据无效
    Address = WRITE_START_ADDR1;
    while((Address < WRITE_END_ADDR)&&(FLASHStatus == FLASH_COMPLETE))
  {
        FLASH_ProgramWord(Address , Data1);
        Address  = Address +4;
    }

  FLASH_Lock();
  
  /* 检查写入的数据是否正确 */
  Address = WRITE_START_ADDR;

  while((Address < WRITE_END_ADDR) && (MemoryProgramStatus != FAILED))
  {
    if((*(__IO uint32_t*) Address) != Data)
    {
      MemoryProgramStatus = FAILED;
    }
    Address += 4;
  }
    return MemoryProgramStatus;
}

 

posted @ 2021-11-14 16:11  InitForever  阅读(60)  评论(0编辑  收藏  举报