MSPM0G3507: FLASH OPERATION

Part Number: MSPM0G3507

Tool/software:

Hi,

I am using MSPM0G3507 launchpad for development.I came across the example codes related to Flash.

I have implemented a basic driver for Flash write:
 
1. Read the whole sector.
2. Modify the bytes
3. Erase the sector
4. Update the Sector

This is the sequence I am using. I will share the code snippet. It is working also.

But I think it is not optimized. If I want to just modify one byte any other method?

#define FLASH_WORD_SIZE 8
#define FLASH_SECTOR_SIZE 1024

/******************************************************* */

int8_t Flash_UpdateSector(uint32_t sectorAddr, uint8_t *newData)
{
DL_FLASHCTL_COMMAND_STATUS gCmdStatus;

// Erase sector
DL_FlashCTL_executeClearStatus(FLASHCTL);
DL_FlashCTL_unprotectSector(FLASHCTL, sectorAddr, DL_FLASHCTL_REGION_SELECT_MAIN);
gCmdStatus = DL_FlashCTL_eraseMemoryFromRAM(FLASHCTL, sectorAddr, DL_FLASHCTL_COMMAND_SIZE_SECTOR);
if (gCmdStatus == DL_FLASHCTL_COMMAND_STATUS_FAILED)
return BOARD_FLASH_ERROR;

// Program back sector (word by word)
for (uint32_t offset = 0; offset < FLASH_SECTOR_SIZE; offset += FLASH_WORD_SIZE)
{
DL_FlashCTL_executeClearStatus(FLASHCTL);
DL_FlashCTL_unprotectSector(FLASHCTL, sectorAddr + offset, DL_FLASHCTL_REGION_SELECT_MAIN);
gCmdStatus = DL_FlashCTL_programMemoryFromRAM64WithECCGenerated(FLASHCTL, sectorAddr + offset,
(uint32_t *)&newData[offset]);
if (gCmdStatus == DL_FLASHCTL_COMMAND_STATUS_FAILED)
return BOARD_FLASH_ERROR;
}

return BOARD_FLASH_OK;
}

int8_t Flash_Write_Bytes(uint32_t address, uint8_t *pData, uint32_t length)
{
uint32_t sectorAddr = address & ~(FLASH_SECTOR_SIZE - 1); // sector base

uint8_t buffer[FLASH_SECTOR_SIZE];

// Copy whole sector into RAM buffer
memcpy(buffer, (void *)sectorAddr, FLASH_SECTOR_SIZE);

// Modify the required bytes
for (uint32_t i = 0; i < length; i++)
{
buffer[(address - sectorAddr) + i] = pData[i];
}

// Reprogram the entire sector
return Flash_UpdateSector(sectorAddr, buffer);
}
  • Hi Paul,

    Unless writing to a clean section of flash, or if you are changing 1s to a 0, modifying or overwriting requires erasing an entire sector first. The only optimizations possible would be to change 1s to 0s without erasing or dynamically change the number of writes being made to Flash from Ram based on the amount of memory actually used in the sector. Also, be aware that if this is application code, it needs to be 8-byte aligned.

    You cannot change a 0 back into a 1 without erasing the sector.

    Your for loop that performs each flash write can be changed to a while loop:

    while((newData[offset] != 0xFFFFF.....) & (offset < FLASH_SECTOR_SIZE))
    {
        Write to Flash
    }

    Best Regards,
    Brian