12.3.1 Flash Read, Erase and Write Code Examples

#include "spi_flash.h"
#define DATA_TO_REPLACE	"THIS IS A NEW SECTOR IN FLASH"

int main()
{
	uint8	au8FlashContent[FLASH_SECTOR_SZ] = {0};
	uint32   u32FlashTotalSize = 0, u32FlashOffset = 0;
	sint8	ret = M2M_SUCCESS;
	// Platform specific initializations.

	ret = m2m_wifi_download_mode();
	if(M2M_SUCCESS != ret) 
	{
		printf("Unable to enter download mode\r\n");
	}
	else
	{
		u32FlashTotalSize = spi_flash_get_size();
	}

	while((u32FlashTotalSize > u32FlashOffset) && (M2M_SUCCESS == ret))
	{
		ret = spi_flash_read(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ);
		if(M2M_SUCCESS != ret)
		{
			printf("Unable to read SPI sector\r\n");
			break;
		}
		memcpy(au8FlashContent, DATA_TO_REPLACE, strlen(DATA_TO_REPLACE));
		
		ret = spi_flash_erase(u32FlashOffset, FLASH_SECTOR_SZ);
		if(M2M_SUCCESS != ret)
		{
			printf("Unable to erase SPI sector\r\n");
			break;
		}
		
		ret = spi_flash_write(au8FlashContent, u32FlashOffset, FLASH_SECTOR_SZ);
		if(M2M_SUCCESS != ret)
		{
			printf("Unable to write SPI sector\r\n");
			break;
		}
		u32FlashOffset += FLASH_SECTOR_SZ;
	}
	
	if(M2M_SUCCESS == ret)
	{
		printf("Successful operations\r\n");
	}
	else
	{
		printf("Failed operations\r\n");
	}
	
	while(1);
	return M2M_SUCCESS;
}