When writing data to SPI Flash, EEPROM and other devices, usually such devices have a Page Buffer inside, and the length of the written data cannot exceed the length of the Page Buffer, otherwise problems will occur. When writing to such devices, a corresponding programming paradigm is proposed.
This article takes SPI Flash as an example, and other devices such as EEPROM can also be referred to.
#define SPI_FLASH_PAGE_SIZE (0x100)
uint32_t SPIFlash_WriteBuffer(uint32_t Address, uint8_t *pBuffer, uint32_t nLength)
{
uint32_t curLength = 0;
uint32_t curAddress = 0;
uint32_t nRemain = 0;
uint32_t nPageRemain = 0;
if ((pBuffer == NULL) || (nLength == 0))
{
return 0;
}
curAddress = Address;
while (curLength < nLength)
{
nPageRemain = SPI_FLASH_PAGE_SIZE - (curAddress & (SPI_FLASH_PAGE_SIZE - 1)); /* adjust max possible size to page boundary. */
nRemain = nLength - curLength;
if (nRemain < nPageRemain)
{
nPageRemain = nRemain;
}
SPIFlash_WritePage(curAddress, pBuffer + curLength, nPageRemain);
curAddress += nPageRemain;
curLength += nPageRemain;
}
SPIFlash_WriteDisable();
return nLength;
}
void SPIFlash_WritePage(uint32_t Address, uint8_t *pBuffer, uint32_t nLength)
{
}
Among them, the Write Page function can be written according to the actual situation.