STM32F411RE Embedded FLASH(internal FLASH) write.

Dependencies:   mbed

main.cpp

Committer:
hiro99ma
Date:
2015-11-30
Revision:
1:fa70127b3381
Parent:
0:23f5942ba14e

File content as of revision 1:fa70127b3381:

#include "mbed.h"
#include "stm32f4xx_hal_flash.h"

#if 1
#define DEBUG_PRINTF        pc.printf
#else
#define DEBUG_PRINTF(...)
#endif

namespace {
    Serial pc(SERIAL_TX, SERIAL_RX);
    
    //STM32F411.C/E(DM00119316.pdf p.43 Table 4)
    const struct {
        uint8_t     sector;
        uint32_t    addr;
    } FLASH_SECTOR[] = {
        {
            FLASH_SECTOR_0,
            (uint32_t)0x08000000      /* Base address of Sector 0,  16 Kbytes  */
        },
        {
            FLASH_SECTOR_1,
            (uint32_t)0x08004000      /* Base address of Sector 1,  16 Kbytes  */
        },
        {
            FLASH_SECTOR_2,
            (uint32_t)0x08008000      /* Base address of Sector 2,  16 Kbytes  */
        },
        {
            FLASH_SECTOR_3,
            (uint32_t)0x0800c000      /* Base address of Sector 3,  16 Kbytes  */
        },
        {
            FLASH_SECTOR_4,
            (uint32_t)0x08010000      /* Base address of Sector 4,  64 Kbytes  */
        },
        {
            FLASH_SECTOR_5,
            (uint32_t)0x08020000      /* Base address of Sector 5, 128 Kbytes  */
        },
        {
            FLASH_SECTOR_6,
            (uint32_t)0x08040000      /* Base address of Sector 6, 128 Kbytes  */
        },
        {
            FLASH_SECTOR_7,
            (uint32_t)0x08060000      /* Base address of Sector 7, 128 Kbytes  */
        }
    };

    /** @brief  内蔵FLASHへのbyte書込み(セクタ消去有り)
     *
     * @param[in]   addr    書込み先アドレス(ADDR_FLASH_SECTOR_x)
     * @param[in]   pData   書き込みデータ
     * @param[in]   Len     書き込みデータサイズ
     */
    void programByte(int sector, const uint8_t *pData, uint8_t Len)
    {
        HAL_StatusTypeDef ret;
    
        /* flash control registerへのアクセス許可 */
        HAL_FLASH_Unlock();
        DEBUG_PRINTF("unlocked.\n");
    
        /* 消去(電圧 [2.7V to 3.6V]) */
        FLASH_Erase_Sector(FLASH_SECTOR[sector].sector, FLASH_VOLTAGE_RANGE_3);
        DEBUG_PRINTF("erased.\n");

        /* 書込み(4byte単位) */
        uint32_t addr = FLASH_SECTOR[sector].addr;
        for (int lp = 0 ; lp < Len; lp++) {
            DEBUG_PRINTF("addr:0x%08x  data=%02x\n", addr, *pData);
            ret = HAL_FLASH_Program(FLASH_TYPEPROGRAM_BYTE, addr, *pData);
            if (ret != HAL_OK) {
                //trouble!!
                DEBUG_PRINTF("fail\n");
                while (true) {}
            }
            addr++;
            pData++;
        }
    
        /* flash control registerへのアクセス禁止 */
        HAL_FLASH_Lock();
    }
    
    const uint8_t *getFlash(int sector) { return (const uint8_t *)FLASH_SECTOR[sector].addr; }
}



int main()
{
    uint8_t str[] = "Hello.";
    
    DEBUG_PRINTF("%s\n", str);
    
    programByte(7, str, sizeof(str));
    
    DEBUG_PRINTF("success[%s]\n", getFlash(7));
}