SPI_Cmd(SPI1,ENABLE);
}
//send a byte through the spi interface and return the byte receive from the SPI bus
u8 SPI_FLASH_SendByte(u8 byte)
{
//等待DR为空
while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_TXE)==RESET);
SPI_I2S_SendData(SPI1,byte);
//等待接收数据
while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_RXNE)==RESET);
return SPI_I2S_ReceiveData(SPI1);
}
//Enable the Write access to the FALSH
void SPI_FLASH_WriteEnable(void)
{
SPI_FLASH_CS_LOW();
//使能 写
SPI_FLASH_SendByte(W25X16_WriteEnable);
SPI_FLASH_CS_HIGH();
}
//wait for write complete
void SPI_FLASH_WaitForWriteEnd(void)
{
u8 FLASH_Status=0;
SPI_FLASH_CS_LOW();
//读状态寄存器
SPI_FLASH_SendByte(W25X16_ReadStatusReg);
do
{
//send a dummy byte to generate the clock needed by the flash
//and return the value of the status register
FLASH_Status=SPI_FLASH_SendByte(Dummy_Byte);
} while((FLASH_Status&WIP_Flag)==SET);
SPI_FLASH_CS_HIGH();
}
// 扇区擦除4KB SectorAddr为起始地址
void SPI_FLASH_SectorErase(u32 SectorAddr)
{
SPI_FLASH_WriteEnable();
SPI_FLASH_WaitForWriteEnd();
//sector erase
SPI_FLASH_CS_LOW();
SPI_FLASH_SendByte(W25X16_SectorErase);
//send sectorAddr high address byte
SPI_FLASH_SendByte((SectorAddr&0xFF0000)>>16);
SPI_FLASH_SendByte((SectorAddr&0xFF00)>>8);
SPI_FLASH_SendByte(SectorAddr&0xFF);
SPI_FLASH_CS_HIGH();
SPI_FLASH_WaitForWriteEnd();
}
// Erase the entire FLASH
void SPI_FLASH_BulkErase(void)
{
SPI_FLASH_WriteEnable();
SPI_FLASH_WaitForWriteEnd();
SPI_FLASH_CS_LOW();
SPI_FLASH_SendByte(W25X16_ChipErase);
SPI_FLASH_CS_HIGH();
SPI_FLASH_WaitForWriteEnd();
}
//Writes more than one bytes to the flash, the number of the byte can not
// exceed the FLASH page size (256)
//此函数只能写入小于等于256个字节