flash.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "flash.h"
  2. u32 STMFLASH_ReadWord(u32 faddr)
  3. {
  4. return *(vu32*)faddr;
  5. }
  6. float ReadFloatWord(u32 faddr)
  7. {
  8. return *(float*)faddr;
  9. }
  10. uint16_t STMFLASH_GetFlashSector(u32 addr)
  11. {
  12. if(addr<ADDR_FLASH_SECTOR_1)return FLASH_Sector_0;
  13. else if(addr<ADDR_FLASH_SECTOR_2)return FLASH_Sector_1;
  14. else if(addr<ADDR_FLASH_SECTOR_3)return FLASH_Sector_2;
  15. else if(addr<ADDR_FLASH_SECTOR_4)return FLASH_Sector_3;
  16. else if(addr<ADDR_FLASH_SECTOR_5)return FLASH_Sector_4;
  17. else if(addr<ADDR_FLASH_SECTOR_6)return FLASH_Sector_5;
  18. else if(addr<ADDR_FLASH_SECTOR_7)return FLASH_Sector_6;
  19. else if(addr<ADDR_FLASH_SECTOR_8)return FLASH_Sector_7;
  20. else if(addr<ADDR_FLASH_SECTOR_9)return FLASH_Sector_8;
  21. else if(addr<ADDR_FLASH_SECTOR_10)return FLASH_Sector_9;
  22. else if(addr<ADDR_FLASH_SECTOR_11)return FLASH_Sector_10;
  23. return FLASH_Sector_11;
  24. }
  25. void STMFLASH_Write(u32 WriteAddr,u32 *pBuffer,u32 NumToWrite)
  26. {
  27. FLASH_Status status = FLASH_COMPLETE;
  28. u32 addrx=0;
  29. u32 endaddr=0;
  30. if(WriteAddr<STM32_FLASH_BASE1||WriteAddr%4)return; //非法地址
  31. FLASH_Unlock(); //解锁
  32. FLASH_DataCacheCmd(DISABLE);//FLASH擦除期间,必须禁止数据缓存
  33. addrx=WriteAddr; //写入的起始地址
  34. endaddr=WriteAddr+NumToWrite*4; //写入的结束地址
  35. if(addrx<0X1FFF0000) //只有主存储区,才需要执行擦除操作!!
  36. {
  37. while(addrx<endaddr) //扫清一切障碍.(对非FFFFFFFF的地方,先擦除)
  38. {
  39. if(STMFLASH_ReadWord(addrx)!=0XFFFFFFFF)//有非0XFFFFFFFF的地方,要擦除这个扇区
  40. {
  41. status=FLASH_EraseSector(STMFLASH_GetFlashSector(addrx),VoltageRange_3);//VCC=2.7~3.6V之间!!
  42. if(status!=FLASH_COMPLETE)break; //发生错误了
  43. }else addrx+=4;
  44. }
  45. }
  46. if(status==FLASH_COMPLETE)
  47. {
  48. while(WriteAddr<endaddr)//写数据
  49. {
  50. if(FLASH_ProgramWord(WriteAddr,*pBuffer)!=FLASH_COMPLETE)//写入数据
  51. {
  52. break; //写入异常
  53. }
  54. WriteAddr+=4;
  55. pBuffer++;
  56. }
  57. }
  58. FLASH_DataCacheCmd(ENABLE); //FLASH擦除结束,开启数据缓存
  59. FLASH_Lock();//上锁
  60. }
  61. void STMFLASH_Read(u32 ReadAddr,u32 *pBuffer,u32 NumToRead)
  62. {
  63. u32 i;
  64. for(i=0;i<NumToRead;i++)
  65. {
  66. pBuffer[i]=STMFLASH_ReadWord(ReadAddr);//读取4个字节.
  67. ReadAddr+=4;//偏移4个字节.
  68. }
  69. }