|
最近用TI的cc2540(51的核,8Kram,128kflash)读写华邦的W25Q16的SPIflash,发现CC2540每一个小时都会定时死机,只有重新上电复位才能重新开始工作,经过多方调试才把问题定位到了是spiflash有问题,但是研究代码又没发现有什么问题!真是纠结了。
我程序的流程是每2秒写一次flash,每次写的数据量是9个字节,写完后spiflash进入休眠,cc2540也进入休眠,2秒的定时到了之后,重复上面的过程,数据是循环写的。
写数据的程序如下:
void spi_flash_BufferWrite(uint8* pBuffer, uint32 WriteAddr, uint16 NumByteToWrite)
{
uint8 Addr = 0, NumOfPage = 0, NumOfSingle = 0, count = 0, temp = 0;
Addr = WriteAddr % SPI_FLASH_PageSize; //某页中的第Addr个地址
count = SPI_FLASH_PageSize - Addr; //某页中还剩余coun个地址空闲
NumOfPage = NumByteToWrite / SPI_FLASH_PageSize; //待写数据占用了页数
NumOfSingle = NumByteToWrite % SPI_FLASH_PageSize; //待写数据写了整数页大小的数据量后还剩多少个字节要写
if (Addr == 0) // 写入的地址刚好在下页地址首地址
{
if (NumOfPage == 0) // 待写入的数据小于一页的容量256
{
spi_flash_PageWrite(pBuffer, WriteAddr, NumByteToWrite);
}
else // 待写入的数据大于一页的容量256
{
while (NumOfPage--)
{
spi_flash_PageWrite(pBuffer, WriteAddr, SPI_FLASH_PageSize);
WriteAddr += SPI_FLASH_PageSize;
pBuffer += SPI_FLASH_PageSize;
}
spi_flash_PageWrite(pBuffer, WriteAddr, NumOfSingle);
}
}
else // 待写入的地址不在某页的首地址
{
if (NumOfPage == 0) // 待写入的数据 < 256字节
{
if (NumOfSingle > count) // 待写入的数据量 + 待写入数据的首地址 > 当前页空余的空间
{
temp = NumOfSingle - count;
spi_flash_PageWrite(pBuffer, WriteAddr, count);
WriteAddr += count;
pBuffer += count;
spi_flash_PageWrite(pBuffer, WriteAddr, temp);
}
else
{
spi_flash_PageWrite(pBuffer, WriteAddr, NumByteToWrite);
}
}
else // 待写入的数据 > 256字节
{
NumByteToWrite -= count;
NumOfPage = NumByteToWrite / SPI_FLASH_PageSize;
NumOfSingle = NumByteToWrite % SPI_FLASH_PageSize;
spi_flash_PageWrite(pBuffer, WriteAddr, count);
WriteAddr += count;
pBuffer += count;
while (NumOfPage--)
{
spi_flash_PageWrite(pBuffer, WriteAddr, SPI_FLASH_PageSize);
WriteAddr += SPI_FLASH_PageSize;
pBuffer += SPI_FLASH_PageSize;
}
if (NumOfSingle != 0)
{
spi_flash_PageWrite(pBuffer, WriteAddr, NumOfSingle);
}
}
}
}
----------------------------------------------------------------------------------------------------------------------------------
void spi_flash_PageWrite(uint8* pBuffer, uint32 WriteAddr, uint16 NumByteToWrite)
{
halspi_cs_low(); // 使能slave
spi_flash_WriteEnable(); // 使能Flash写操作
spi_flash_SendByte(W25X_PageProgram); // 发送 "Write to Memory " 指令
//if(WriteAddr >= 0x1fffff) WriteAddr = START_WRITE_LOCATION;//写到片尾,从第三个sector手开始从新写
spi_flash_SendByte((WriteAddr & 0xFF0000) >> 16); // 发送待写入地址的高地址位
spi_flash_SendByte((WriteAddr & 0xFF00) >> 8); // 发送待写入地址的中间不服地址位
spi_flash_SendByte(WriteAddr & 0xFF); // 发送待写入地址的低地址位
if(NumByteToWrite > SPI_FLASH_PerWritePageSize)
{
NumByteToWrite = SPI_FLASH_PerWritePageSize;
}
while (NumByteToWrite--) // 循环写数据
{
spi_flash_SendByte(*pBuffer); // 发送当前待写入的数据
pBuffer++; // 下一个待写入数据
}
halspi_cs_high(); // 禁用slave
spi_flash_WaitForWriteEnd(); // 等待Flash写操作结束
}
|
|