.

ROMSLOT_STM32.cpp

Committer:
va009039
Date:
2016-04-08
Revision:
1:dee9fae0c0c4

File content as of revision 1:dee9fae0c0c4:

// ROMSLOT_STM32.cpp 2016/4/7
#if defined(TARGET_STM)
#include "ROMSLOT.h"

bool ROMSLOT::Write(uint32_t addr, const uint8_t buf[], uint32_t size) {
    MBED_ASSERT(addr%FLASH_PAGE_SIZE == 0);
    MBED_ASSERT(size%FLASH_PAGE_SIZE == 0);
    if (memcmp((uint8_t*)addr, buf, size) == 0) { // skip ?
        return true;
    }
    HAL_FLASH_Unlock();
    bool result = true;
    for(uint32_t n = 0; n < size; n += sizeof(uint32_t)) {
        if (n % FLASH_PAGE_SIZE == 0) {
            FLASH_EraseInitTypeDef Erase;
            Erase.NbPages = 1;
            Erase.TypeErase = TYPEERASEDATA_BYTE;
            Erase.PageAddress = addr + n;
            uint32_t PageError = 0;
            HAL_StatusTypeDef status = HAL_FLASHEx_Erase(&Erase, &PageError);
            MBED_ASSERT(status == HAL_OK);
            if (status != HAL_OK) {
                result = false;
                break;
            }
        }
        uint32_t data = buf[n]|buf[n+1]<<8|buf[n+2]<<16|buf[n+3]<<24;
        HAL_StatusTypeDef status = HAL_FLASH_Program(TYPEPROGRAM_WORD, addr + n, (uint64_t)data);
        MBED_ASSERT(status == HAL_OK);
        if (status != HAL_OK) {
            result = false;
            break;
        }
    }
    HAL_FLASH_Lock();
    return result;
}
#endif // TARGET_STM