#include "spiFlash.h" #include #include "nwy_spi.h" #define Xm25_JedecDeviceID 0x9f #define Xm25_SectorEarse 0x20 #define Xm25_ReadData 0x03 #define Xm25_WriteEnable 0x06 #define Xm25_PageProgram 0x02 #define Xm25_ReadStatusReg 0x05 #define PAGE_RW_SIZE 256 static int spiFlashFp=SPI_EC_ERROR; /*外部SPI FLASH初始化*/ bool spiFlashInit(void){ int fp=SPI_EC_ERROR; if(SPI_EC_ERROR!=spiFlashFp) return true; fp=nwy_spi_init(NAME_SPI_BUS_1, SPI_MODE_0, 8000000, 8); if(fp==SPI_EC_ERROR) return false; spiFlashFp=fp; return true; } /*释放SPI FLASH接口*/ void spiFlashDeInit(void){ if(spiFlashFp==SPI_EC_ERROR) return; nwy_spi_deinit(spiFlashFp); spiFlashFp=SPI_EC_ERROR; } /*读取SPI FLASH 设备ID*/ unsigned int spiFlashGetID(void){ if(spiFlashFp==SPI_EC_ERROR) return 0; return nwy_read_flash_id(spiFlashFp, Xm25_JedecDeviceID); } /*SPI FLASH sector擦出*/ bool spiFlashSectorErace(unsigned int addr){ if(spiFlashFp==SPI_EC_ERROR) return false; if(addr % SECTOR_SIZE_BYTE) return false; nwy_spi_flash_sector_erase(spiFlashFp,Xm25_WriteEnable,Xm25_ReadStatusReg,Xm25_SectorEarse,addr); return true; } /*SPI FLASH写数据*/ bool spiFlashDataWrite(unsigned int addr, unsigned char *data_ptr, int size){ int i,len; if(spiFlashFp==SPI_EC_ERROR) return false; i=size; while(i>0){ if(i>PAGE_RW_SIZE) len=PAGE_RW_SIZE; else len=i; nwy_spi_flash_write(spiFlashFp, Xm25_WriteEnable,Xm25_ReadStatusReg,Xm25_PageProgram, data_ptr, addr, len); i -= len; } return true; } /*SPI FLASH读数据*/ bool spiFlashDataRead(unsigned int addr, unsigned char *rec_ptr, int size){ int i,len,j; if(spiFlashFp==SPI_EC_ERROR) return false; i=size; j=0; while(i>0){ if(i>PAGE_RW_SIZE) len=PAGE_RW_SIZE; else len=i; nwy_spi_flash_read(spiFlashFp,Xm25_ReadData, rec_ptr+j, addr, len); i -= len; j += len; } return true; } #ifdef TEST_SPIFLASH_ON /*SPI FLASH SECTOR 测试*/ bool spiFlashSectorTest(unsigned short sector, SPIFLASH_INFO *spiFlashInfo){ unsigned int addr; unsigned char Winfo[PAGE_RW_SIZE]; unsigned char Rinfo[PAGE_RW_SIZE]; int i,len; static unsigned char w=0; if(false==spiFlashInit()){ spiFlashInfo->id=0; spiFlashInfo->errno=1; return false; } spiFlashInfo->id=spiFlashGetID(); addr=sector*SECTOR_SIZE_BYTE; if(false==spiFlashSectorErace(addr)){ spiFlashInfo->errno=2; return false; } for(i=0;i0){ if(i>PAGE_RW_SIZE) len=PAGE_RW_SIZE; else len=i; if(false==spiFlashDataWrite(addr, Winfo, len)){ spiFlashInfo->errno=3; spiFlashDeInit(); return false; } addr += len; i -= len; } addr=sector*SECTOR_SIZE_BYTE; i=SECTOR_SIZE_BYTE; while(i>0){ if(i>PAGE_RW_SIZE) len=PAGE_RW_SIZE; else len=i; memset(Rinfo, 0, PAGE_RW_SIZE); if(false==spiFlashDataRead(addr, Rinfo, len)){ spiFlashInfo->errno=4; spiFlashDeInit(); return false; } addr += len; i -= len; if(0!=memcmp(Winfo, Rinfo, len)){ spiFlashInfo->errno=5; spiFlashDeInit(); return false; } } return true; } #endif