0

我正在尝试将任何大小的结构写入 STM32H7 的闪存。它只写了 4 个字节的倍数。未写入剩余字节 (1, 2, 3)。我使用临时变量来存储剩余字节。在调试中,temp 的值是正确的,但它没有存储在闪存中。有什么建议如何将剩余字节写入闪存:)?

void flashWriteN(uint32_t sectorAddr, uint32_t idx, volatile void *buf,
        uint32_t Nsize) {
    uint8_t* wrBuf = (uint8_t *)buf;
    uint32_t flashAddress = sectorAddr + idx;
    uint32_t temp = 0;
    uint8_t offset = Nsize%4;
    HAL_FLASH_Unlock();
    switch (offset) {
    case 1:
        temp = wrBuf[Nsize-1];
        break;
    case 2:
        temp = ((wrBuf[Nsize-2] << 8) + wrBuf[Nsize-1]);
        break;
    case 3:
        temp = ((wrBuf[Nsize-3] << 16) + (wrBuf[Nsize-2] << 8) + wrBuf[Nsize-1]);
        break;
    default:
        break;
    }
    for (uint32_t i = 0; i < Nsize / 4; i += 4) {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, flashAddress,
                (uint32_t) (&((uint32_t*) wrBuf)[i]));
        flashAddress += 4;
    }
    if (offset!=0) {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, flashAddress,
                        (uint32_t)&temp);
    }
    HAL_FLASH_Lock();
}
4

0 回答 0