5.14 Flash Guide

This chapter covers the files of the Flash driver in the N32H49x standard peripheral library, its 55 public functions, and 6 examples: DualBankSwap, Flash_Program, Flash_Row_Program, OptionByte_Config, Run_In_CCM, and SingleBankRemap. Read it together with the “Memory and bus architecture” chapter of the user manual for read wait states, program/erase unlock, option bytes, write protection, and dual-bank behavior.

5.14.1 Related files

Relative path Purpose
firmware/n32h49x_std_periph_driver/inc/n32h49x_flash.h Defines the FLASH_STS status enum and the read-protection, interrupt-flag, option-byte, write-protection page, and row-program macros;
declares the 55 public functions
firmware/n32h49x_std_periph_driver/src/n32h49x_flash.c Implements the 55 functions: wait-state and cache control, program/erase unlock sequences, page and bank erase, double-word and row programming, option-byte program and read, flag and interrupt handling, and CCM SRAM control
projects/n32h49x_EVAL/examples/Flash/ Flash example root, containing 6 examples: DualBankSwap, Flash_Program, Flash_Row_Program, OptionByte_Config, Run_In_CCM, SingleBankRemap
projects/n32h49x_EVAL/examples/Flash/Flash_Program/ Project layout of that example: MDK-ARM/, EWARM/, inc/, src/, readme.txt
projects/n32h49x_EVAL/bsp/ Board support files shared by the 6 examples: board LED definitions, USART log initialization, and the millisecond delay function

5.14.2 API reference

Search API55 functions

The following 55 public functions are listed in the declaration order of n32h49x_flash.h in 9 groups; each entry gives a summary and the original comment above the function in n32h49x_flash.c.

Fetch latency and cache

FLASH_SetLatency, FLASH_GetLatency, FLASH_PrefetchBufSet, FLASH_iCacheRST, FLASH_iCacheCmd, FLASH_DCacheRST, FLASH_DCacheCmd

Unlock and lock

FLASH_Unlock, FLASH_Lock, Flash_GetLockStatus, Option_Bytes_Unlock, Option_Bytes_Lock, OB_GetLockStatus

Erase

FLASH_EraseOnePage, FLASH_MassErase, FLASH_BankErase

Programming

FLASH_ProgramdoubleWord, FLASH_RowProgramSet, FLASH_RowProgramAreaSet, FLASH_RowProgram

Option-byte programming

FLASH_EraseOB, FLASH_ProgramOB_RRDC, FLASH_ProgramOB_U1U2, FLASH_EnWriteProtection, FLASH_ProgramOB_Data, FLASH_ProgramOB_SRAMECC, FLASH_ReadOutProtectionL1, FLASH_ReadOutProtectionL2_ENABLE

Option-byte read

FLASH_GetUserOB, FLASH_GetUser2, FLASH_GetOptionBytes_Data0, FLASH_GetOptionBytes_Data1, FLASH_GetWriteProtectionSTS, FLASH_GetReadOutProtectionSTS, FLASH_GetReadOutProtectionL2STS, FLASH_GetPrefetchBufSTS

Interrupts and flags

FLASH_INTConfig, FLASH_GetFlagSTS, FLASH_ClearFlag, FLASH_GetSTS, FLASH_WaitForLastOpt

CCM SRAM

CCM_EnWriteProtection, CCM_GetWriteProtectionSTS, CCM_Earse_Unlock, CCM_EarseEN, CCM_EarseSTS, CCM_ModeSet

Decryption and UID

XSPI_DESRangeSet, FEMC_DESRangeSet, RTP_DESKeySet, GetRTP_DESKeyWnum, Jtag_SealSet, XSPI_FEMC_DESSet, Get_XFUID, Get_CCMUID

void FLASH_SetLatency(uint32_t FLASH_Latency)Sets the code latency value.
Source comment
name    FLASH_SetLatency
fun     Sets the code latency value.
param   FLASH_Latency :(The input parameters must be the following values)
            - FLASH_LATENCY_0    FLASH Zero Latency cycle, 0 < SYSCLK <= 48MHz
            - FLASH_LATENCY_1    FLASH One Latency cycle, 48MHz < SYSCLK<= 96MHz
            - FLASH_LATENCY_2    FLASH Two Latency cycle, 96MHz < SYSCLK<= 144MHz
            - FLASH_LATENCY_3    FLASH Three Latency cycle,144MHz < SYSCLK<= 192MHz
            - FLASH_LATENCY_4    FLASH Four Latency cycle, 192MHz < SYSCLK<= 240MHz
return  none
note    The larger the latency, the longer the flash read operation will take.
        If not necessary, it is recommended to use a smaller latency.
uint8_t FLASH_GetLatency(void)Get the code latency value.
Source comment
name    FLASH_GetLatency
fun     Get the code latency value.
param   none
return  FLASH_LATENCY :(The input parameters must be the following values)
            - FLASH_LATENCY_0    FLASH Zero Latency cycle, 0 < SYSCLK <= 48MHz
            - FLASH_LATENCY_1    FLASH One Latency cycle, 48MHz < SYSCLK<= 96MHz
            - FLASH_LATENCY_2    FLASH Two Latency cycle, 96MHz < SYSCLK<= 144MHz
            - FLASH_LATENCY_3    FLASH Three Latency cycle,144MHz < SYSCLK<= 192MHz
            - FLASH_LATENCY_4    FLASH Four Latency cycle, 192MHz < SYSCLK<= 240MHz
void FLASH_PrefetchBufSet(uint32_t FLASH_PrefetchBuf)Enables or disables the Prefetch Buffer.
Source comment
name    FLASH_PrefetchBufSet
fun     Enables or disables the Prefetch Buffer.
param   FLASH_PrefetchBuf:(The input parameters must be the following values)
            - FLASH_PrefetchBuf_EN
            - FLASH_PrefetchBuf_DIS
return  none
note  Prefetch feature must be disabled for this bit.
void FLASH_iCacheRST(uint32_t Bank)ICache Reset.
Source comment
name    FLASH_iCacheRST
fun     ICache Reset.
param   Bank:(The input parameters must be the following values)
            - FLASH_BANK1
            - FLASH_BANK2
return  none
void FLASH_iCacheCmd(uint32_t Bank, uint32_t FLASH_iCache)Enables or disables the iCache.
Source comment
name    FLASH_iCacheCmd
fun     Enables or disables the iCache.
param   Bank:(The input parameters must be the following values)
            - FLASH_BANK1
            - FLASH_BANK2
param   FLASH_iCache:(The input parameters must be the following values)
            - FLASH_iCache_EN FLASH iCache Enable
            - FLASH_iCache_DIS FLASH iCache Disable
return  none
void FLASH_DCacheRST(void)DCache Reset.
Source comment
name    FLASH_DCacheRST
fun     DCache Reset.
param   none
return  none
void FLASH_DCacheCmd(uint32_t FLASH_DCache)Enables or disables the DCache.
Source comment
name    FLASH_DCacheCmd
fun     Enables or disables the DCache.
param   FLASH_DCache:(The input parameters must be the following values)
            - FLASH_DCache_EN FLASH DCache Enable
            - FLASH_DCache_DIS FLASH DCache Disable
return  none
note
void FLASH_Unlock(void)Unlocks the FLASH Program Erase Controller.
Source comment
name   FLASH_Unlock
fun    Unlocks the FLASH Program Erase Controller.
param  none
return none
void FLASH_Lock(void)Locks the FLASH Program Erase Controller.
Source comment
name   FLASH_Lock
fun    Locks the FLASH Program Erase Controller.
param  none
return none
FlagStatus Flash_GetLockStatus(void)Get the Flash lock status.
Source comment
name   Flash_GetLockStatus
fun    Get the Flash lock status.
param  none
return FlagStatus :
            - SET     FLASH is in Lock state
            - RESET   FLASH is in Unlock state
void Option_Bytes_Unlock(void)Unlocks the Option_Bytes Program Erase Controller.
Source comment
name   Option_Bytes_Unlock
fun    Unlocks the Option_Bytes Program Erase Controller.
param  none
return none
void Option_Bytes_Lock(void)Locks the Option_Bytes Program Erase Controller.
Source comment
name   Option_Bytes_Lock
fun    Locks the Option_Bytes Program Erase Controller.
param  none
return none
FlagStatus OB_GetLockStatus(void)Get the Option Bytes lock status.
Source comment
name   OB_GetLockStatus
fun    Get the Option Bytes lock status.
param  none
return FlagStatus :
            - SET     Option byte is in Lock state
            - RESET   Option byte is in Unlock state
FLASH_STS FLASH_EraseOnePage(uint32_t Page_Address)Erases a specified main FLASH page.
Source comment
name   FLASH_EraseOnePage
fun    Erases a specified main FLASH page.
param  Page_Address :(The input parameters must be the following values)
            - it ranges from 0x08000000 to 0x080FFFFF
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_ADD  FLASH address error
note    If FLASH is in single bank mode,Page_Address must be a multiple of 0x4000;
        If FLASH is in dual bank mode,Page_Address must be a multiple of 0x2000.
FLASH_STS FLASH_MassErase(void)Erases all main FLASH pages.
Source comment
name   FLASH_MassErase
fun    Erases all main FLASH pages.
param  none
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_BankErase(uint32_t Bank)Erases Bank’s all main FLASH pages.
Source comment
name   FLASH_BankErase
fun    Erases Bank's all main FLASH pages.
param   Bank:(The input parameters must be the following values)
            - FLASH_BANK1
            - FLASH_BANK2
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ProgramdoubleWord(uint32_t address, uint32_t data0,uint32_t data1)Programs two words at a specified address.
Source comment
name   FLASH_ProgramdoubleWord
fun    Programs two words at a specified address.
param  address :(The input parameters must be the following values)
            - main flash, it ranges from 0x08000000 to 0x080FFFFF, it must be a multiple of 0x08
param  data0 :(The input parameters must be the following values)
            - It ranges from 0x00000000 to 0xFFFFFFFF
param  data1 :(The input parameters must be the following values)
            - It ranges from 0x00000000 to 0xFFFFFFFF
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_ADD  FLASH address error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
            - FLASH_TIMEOUT  FLASH operation timeout
void FLASH_RowProgramSet(FunctionalState Cmd)Enables or disables row programmer.
Source comment
name   FLASH_RowProgramSet
fun    Enables or disables row programmer.
param  Cmd :(The input parameters must be the following values)
            - ENABLE  Enable Row programmer
            - DISABLE Disable Row programmer
return none
void FLASH_RowProgramAreaSet(FunctionalState Cmd)Configure row programmer area.
Source comment
name   FLASH_RowProgramAreaSet
fun    Configure row programmer area.
param  Cmd :(The input parameters must be the following values)
            - ENABLE  Row programmer in system memory
            - DISABLE Row programmer in main flash
return none
FLASH_STS FLASH_RowProgram(uint32_t address, uint32_t row_num, uint32_t *data)Programs x words at a specified address.
Source comment
name   FLASH_RowProgram
fun    Programs x words at a specified address.
param  address :(The input parameters must be the following values)
            - main flash, it ranges from 0x08000000 to 0x080FFFFF, it must be a multiple of 0x08
param  row_num :(The input parameters must be the following values)
            - It ranges from 0x02 to 0x10,it must be a multiple of 0x02
param  data[] :(The input parameters must be the following values)
            - It ranges from 0x00000000 to 0xFFFFFFFF
return FLASH_STS :
            - FLASH_BUSY        FLASH is busy
            - FLASH_ERR_PG      FLASH programming error
            - FLASH_ERR_WRP     FLASH Write protected error
            - FLASH_EOP         FLASH End of Operation
            - FLASH_ERR_PV      Programmer Verification Error
            - FLASH_ERR_EV      Erase Verification Error
            - FLASH_ERR_ADD     FLASH address error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
            - FLASH_TIMEOUT     FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
note Row programming cannot span 512 bytes.
FLASH_STS FLASH_EraseOB(void)Erases the FLASH option bytes.
Source comment
name   FLASH_EraseOB
fun    Erases the FLASH option bytes.
param  none
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ProgramOB_RRDC(uint32_t option_byte_rpd1, uint32_t option_byte_rpd2, \ uint32_t option_byte_DBANK,uint32_t option_byte_CCMSRAM)Programs the Option Byte: RDP1/RDP2/DBANK/CCMSRAM_RST.
Source comment
name   FLASH_ProgramOB_RRDC
fun    Programs the Option Byte: RDP1/RDP2/DBANK/CCMSRAM_RST.
param  option_byte_rpd1 :(The input parameters must be the following values)
            - FLASH_OB_RDP1_ENABLE   Enable read protection L1
            - FLASH_OB_RDP1_DISABLE  Disable read protection L1
param  option_byte_rpd2 :(The input parameters must be the following values)
            - FLASH_OB_RDP2_ENABLE   Enable read protection L2
            - FLASH_OB_RDP2_DISABLE  Disable read protection L2
param  option_byte_DBANK :(The input parameters must be the following values)
            - FLASH_SINGLE_BANK      Single Bank Mode
            - FLASH_DUAL_BANK        Dual Bank Mode
param  option_byte_CCMSRAM :(The input parameters must be the following values)
            - CCMSRAM_RST_NERASE   CCMSRAM reset not erase
            - CCMSRAM_RST_ERASE    CCMSRAM reset erase
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ProgramOB_U1U2(uint32_t option_byte_iwdg, uint32_t option_byte_stop,\ uint32_t option_byte_stdby, uint32_t option_byte_iwdg_stop, uint32_t option_byte_iwdg_stdby,\ uint32_t option_byte_iwdg_sleep,uint32_t option_byte2_nBOOT0, uint32_t option_byte2_nBOOT1,\ uint32_t option_byte2_nSWBOOT0, uint32_t option_byte2_FlashBoot,uint32_t option_byte2_DAC,\ uint32_t option_byte2_BOR)Programs the Option Byte: USER/USER2.
Source comment
name   FLASH_ProgramOB_U1U2
fun    Programs the Option Byte: USER/USER2.
param  option_byte_iwdg :(The input parameters must be the following values)
            - FLASH_OB_IWDG_SOFTWARE Software IWDG selected
            - FLASH_OB_IWDG_HARDWARE Hardware IWDG selected
param  option_byte_stop :(The input parameters must be the following values)
            - FLASH_OB_STOP_NORST No reset generated when entering in STOP
            - FLASH_OB_STOP_RST Reset generated when entering in STOP
param  option_byte_stdby :(The input parameters must be the following values)
            - FLASH_OB_STDBY_NORST No reset generated when entering in standby
            - FLASH_OB_STDBY_RST Reset generated when entering in standby
param  option_byte_iwdg_stop :(The input parameters must be the following values)
            - FLASH_OB_IWDG_STOP_FRZ IWDG freeze in stop
            - FLASH_OB_IWDG_STOP_NOFRZ Default no freeze
param  option_byte_iwdg_stdby :(The input parameters must be the following values)
            - FLASH_OB_IWDG_STDBY_FRZ IWDG freeze in standby
            - FLASH_OB_IWDG_STDBY_NOFRZ Default no freeze
param  option_byte_iwdg_sleep :(The input parameters must be the following values)
            - FLASH_OB_IWDG_SLEEP_FRZ IWDG freeze in sleep
            - FLASH_OB_IWDG_SLEEP_NOFRZ Default no freeze
param   option_byte2_nBOOT0 :(The input parameters must be the following values)
            - FLASH_OB2_NBOOT0_SET Set nBOOT0
            - FLASH_OB2_NBOOT0_CLR Clear nBOOT0
param   option_byte2_nBOOT1 :(The input parameters must be the following values)
            - FLASH_OB2_NBOOT1_SET Set nBOOT1
            - FLASH_OB2_NBOOT1_CLR Clear nBOOT1
param   option_byte2_nSWBOOT0 :(The input parameters must be the following values)
            - FLASH_OB2_NSWBOOT0_SET Set nSWBOOT0
            - FLASH_OB2_NSWBOOT0_CLR Clear nSWBOOT0
param   option_byte2_FlashBoot :(The input parameters must be the following values)
            - FLASH_OB2_FLASHBOOT_SET Main flash forward section boot
            - FLASH_OB2_FLASHBOOT_CLR Main flash back part boot
param   option_byte2_DAC :(The input parameters must be the following values)
            - FLASH_OB2_DAC_SET System reset, DAC voltage value maintained
            - FLASH_OB2_DAC_CLR System reset, DAC voltage value not maintained
param   option_byte2_BOR :(The input parameters must be the following values)
            - BOR_LEVEL_1_6V Reset level threshold 1.6V (Up 1.66V / Down 1.62V)
            - BOR_LEVEL_2_0V Reset level threshold 2.0V (Up 2.1V / Down 2.0V)
            - BOR_LEVEL_2_2V Reset level threshold 2.2V (Up 2.3V / Down 2.2V)
            - BOR_LEVEL_2_5V Reset level threshold 2.5V (Up 2.6V / Down 2.5V)
            - BOR_LEVEL_2_8V Reset level threshold 2.8V (Up 2.9V / Down 2.8V)
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_EnWriteProtection(uint32_t FLASH_Pages)Write protects the desired pages.
Source comment
name   FLASH_EnWriteProtection
fun    Write protects the desired pages.
param  FLASH_Pages :(The input parameters must be the following values)
            - FLASH_WRP_NUM0   Single Bank: page 0 to 1  , Dual Banke: page 0   to 3
            - FLASH_WRP_NUM1   Single Bank: page 2 to 3  , Dual Banke: page 4   to 7
            - FLASH_WRP_NUM2   Single Bank: page 4 to 5  , Dual Banke: page 8   to 11
            - FLASH_WRP_NUM3   Single Bank: page 6 to 7  , Dual Banke: page 12  to 15
            - FLASH_WRP_NUM4   Single Bank: page 8 to 9  , Dual Banke: page 16  to 19
            - FLASH_WRP_NUM5   Single Bank: page 10 to 11, Dual Banke: page 20  to 23
            - FLASH_WRP_NUM6   Single Bank: page 12 to 13, Dual Banke: page 24  to 27
            - FLASH_WRP_NUM7   Single Bank: page 14 to 15, Dual Banke: page 28  to 31
            - FLASH_WRP_NUM8   Single Bank: page 16 to 17, Dual Banke: page 32  to 35
            - FLASH_WRP_NUM9   Single Bank: page 18 to 19, Dual Banke: page 36  to 39
            - FLASH_WRP_NUM10  Single Bank: page 20 to 21, Dual Banke: page 40  to 43
            - FLASH_WRP_NUM11  Single Bank: page 22 to 23, Dual Banke: page 44  to 47
            - FLASH_WRP_NUM12  Single Bank: page 24 to 25, Dual Banke: page 48  to 51
            - FLASH_WRP_NUM13  Single Bank: page 26 to 27, Dual Banke: page 52  to 55
            - FLASH_WRP_NUM14  Single Bank: page 28 to 29, Dual Banke: page 56  to 59
            - FLASH_WRP_NUM15  Single Bank: page 30 to 31, Dual Banke: page 60  to 63
            - FLASH_WRP_NUM16  Single Bank: page 32 to 33, Dual Banke: page 64  to 67
            - FLASH_WRP_NUM17  Single Bank: page 34 to 35, Dual Banke: page 68  to 71
            - FLASH_WRP_NUM18  Single Bank: page 36 to 37, Dual Banke: page 72  to 75
            - FLASH_WRP_NUM19  Single Bank: page 38 to 39, Dual Banke: page 76  to 79
            - FLASH_WRP_NUM20  Single Bank: page 40 to 41, Dual Banke: page 80  to 83
            - FLASH_WRP_NUM21  Single Bank: page 42 to 43, Dual Banke: page 84  to 87
            - FLASH_WRP_NUM22  Single Bank: page 44 to 45, Dual Banke: page 88  to 91
            - FLASH_WRP_NUM23  Single Bank: page 46 to 47, Dual Banke: page 92  to 95
            - FLASH_WRP_NUM24  Single Bank: page 48 to 49, Dual Banke: page 96  to 99
            - FLASH_WRP_NUM25  Single Bank: page 50 to 51, Dual Banke: page 100 to 103
            - FLASH_WRP_NUM26  Single Bank: page 52 to 53, Dual Banke: page 104 to 107
            - FLASH_WRP_NUM27  Single Bank: page 54 to 55, Dual Banke: page 108 to 111
            - FLASH_WRP_NUM28  Single Bank: page 56 to 57, Dual Banke: page 112 to 115
            - FLASH_WRP_NUM29  Single Bank: page 58 to 59, Dual Banke: page 116 to 119
            - FLASH_WRP_NUM30  Single Bank: page 60 to 61, Dual Banke: page 120 to 123
            - FLASH_WRP_NUM31  Single Bank: page 62 to 63, Dual Banke: page 124 to 127
            - FLASH_WRP_AllPages      all Pages
            - ~FLASH_WRP_AllPages     Disable Write protection of all Pages
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ProgramOB_Data(uint32_t option_byte_data0, uint32_t option_byte_data1,\ uint32_t option_byte_data2, uint32_t option_byte_data3)Programs the Option Byte: DATA0/DATA1/DATA2/DATA3.
Source comment
name   FLASH_ProgramOB_Data
fun    Programs the Option Byte: DATA0/DATA1/DATA2/DATA3.
param  option_byte_data0:(The input parameters must be the following values)
            - 0x00 to 0xFF
param  option_byte_data1:(The input parameters must be the following values)
            - 0x00 to 0xFF
param  option_byte_data2:(The input parameters must be the following values)
            - 0x00 to 0xFF
param  option_byte_data3:(The input parameters must be the following values)
            - 0x00 to 0xFF
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ProgramOB_SRAMECC(uint32_t option_byte_SRAM2,uint32_t option_byte_SRAM3)Programs the Option Byte: SRAM2_ECC_ENABLE,SRAM3_ECC_ENABLE.
Source comment
name   FLASH_ProgramOB_SRAMECC
fun    Programs the Option Byte: SRAM2_ECC_ENABLE,SRAM3_ECC_ENABLE.
param  option_byte_SRAM2 :(The input parameters must be the following values)
            - SRAM2_ECC_ENABLE   SRAM2 ECC ENABLE
            - SRAM2_ECC_DISABLE  SRAM2 ECC DISABLE
param  option_byte_SRAM3 :(The input parameters must be the following values)
            - SRAM3_ECC_ENABLE   SRAM3 ECC ENABLE
            - SRAM3_ECC_DISABLE  SRAM3 ECC DISABLE
return FLASH_STS : (The input parameters must be the following values)
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_ReadOutProtectionL1(FunctionalState Cmd)Enables or disables the read out protection.
Source comment
name   FLASH_ReadOutProtectionL1
fun    Enables or disables the read out protection.
param  Cmd:(The input parameters must be the following values)
            - ENABLE   Enable read protection L1
            - DISABLE  Disable read protection L1
return FLASH_STS : (The input parameters must be the following values)
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
note   If the user has already programmed the other option bytes before calling
       this function, he must re-program them since this function erases all option bytes.
FLASH_STS FLASH_ReadOutProtectionL2_ENABLE(void)Enables the read out protection L2.
Source comment
name   FLASH_ReadOutProtectionL2_ENABLE
fun    Enables the read out protection L2.
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RDP2 FLASH is in read protection L2 status
            - FLASH_TIMEOUT  FLASH operation timeout
            - FLASH_ERR_RPADD   FLASH Row programmer address error
note   If the user has already programmed the other option bytes before calling
       this function, he must re-program them since this function erases all option bytes.
uint32_t FLASH_GetUserOB(void)Returns the FLASH User Option Bytes values.
Source comment
name   FLASH_GetUserOB
fun    Returns the FLASH User Option Bytes values.
param  none
return The FLASH User Option Bytes values:IWDG_SW(Bit0), nRST_STOP(Bit1),
       nRST_STDBY(Bit2), IWDGSTOPFRZ(Bit3), IWDGSTDBYFRZ(Bit5) and IWDGSLEEPFRZ(Bit6).
FlagStatus FLASH_GetUser2(uint32_t option_byte_bit)Returns the FLASH User2 Option Bytes values.
Source comment
name   FLASH_GetUser2
fun    Returns the FLASH User2 Option Bytes values.
param  option_byte_bit: (The input parameters must be the following values)
            - FLASH_OB2_NBOOT0_SET          nBOOT0 configuration bit
            - FLASH_OB2_NBOOT1_SET          nBOOT1 configuration bit
            - FLASH_OB2_NSWBOOT0_SET        nSWBOOT0 configuration bit
return FlagStatus :
            - SET      Enter this mode without resetting
            - RESET    Enter this mode reset
uint32_t FLASH_GetOptionBytes_Data0(void)Returns the FLASH User Option Bytes values.
Source comment
name   FLASH_GetOptionBytes_Data0
fun    Returns the FLASH User Option Bytes values.
param  none
return data0:
            - 0x00 to 0xFF.
uint32_t FLASH_GetOptionBytes_Data1(void)Returns the FLASH User Option Bytes values.
Source comment
name   FLASH_GetOptionBytes_Data1
fun    Returns the FLASH User Option Bytes values.
param  none
return data1:
            - 0x00 to 0xFF.
uint32_t FLASH_GetWriteProtectionSTS(void)Returns the FLASH Write Protection Option Bytes Register value.
Source comment
name   FLASH_GetWriteProtectionSTS
fun    Returns the FLASH Write Protection Option Bytes Register value.
param  none
return The FLASH Write Protection  Option Bytes Register value :
            - Bit31 - Bit0 write-protects dual bank: pages (62~63) - page (0~1)
FlagStatus FLASH_GetReadOutProtectionSTS(void)Checks whether the FLASH Read Out Protection L1 status_value is set or not.
Source comment
name   FLASH_GetReadOutProtectionSTS
fun    Checks whether the FLASH Read Out Protection L1 status_value is set or not.
param  none
return FlagStatus :
        - SET    Read protection L1 enable
        - RESET  Read protection L1 disable
FlagStatus FLASH_GetReadOutProtectionL2STS(void)Checks whether the FLASH Read Out Protection L2 status_value is set or not.
Source comment
name   FLASH_GetReadOutProtectionL2STS
fun    Checks whether the FLASH Read Out Protection L2 status_value is set or not.
param  none
return FlagStatus :
        - SET    Read protection L2 enable
        - RESET  Read protection L2 disable
FlagStatus FLASH_GetPrefetchBufSTS(void)Checks whether the FLASH Prefetch Buffer status_value is set or not.
Source comment
name   FLASH_GetPrefetchBufSTS
fun    Checks whether the FLASH Prefetch Buffer status_value is set or not.
param  none
return FlagStatus :
        - SET    Flash prefetch buffer enable
        - RESET  Flash prefetch buffer disable
void FLASH_INTConfig(uint32_t FLASH_INT, FunctionalState Cmd)Enables or disables the specified FLASH interrupts.
Source comment
name   FLASH_INTConfig
fun    Enables or disables the specified FLASH interrupts.
param  Cmd:(The input parameters must be the following values)
            - ENABLE
            - DISABLE
param  FLASH_INT :
            - FLASH_INT_EOP      FLASH end of operation Interrupt
            - FLASH_INT_ERR      PGERR WRPERR ERROR interrupt source
            - FLASH_INT_FERR     EVERR PVERR ERROR interrupt source
            - FLASH_INT_ECC1     1 bit ECC error interrupt source
            - FLASH_INT_JS       jtag seal error interrupt source
            - FLASH_INT_ECC2     2 bit ECC error interrupt source
            - FLASH_INT_DECC     XSPI/FEMC decryption misconfiguration interrupt source
            - FLASH_INT_RPADD    Row programmer address error interrupt source
            - FLASH_INT_BANKEX   BANK exchange error interrupt Enable
return none
FlagStatus FLASH_GetFlagSTS(uint32_t FLASH_FLAG)Checks whether the specified FLASH flag is set or not.
Source comment
name   FLASH_GetFlagSTS
fun    Checks whether the specified FLASH flag is set or not.
param  FLASH_FLAG :(The input parameters must be the following values)
            - FLASH_FLAG_EOP        FLASH End of Operation flag
            - FLASH_FLAG_BUSY       FLASH Busy flag
            - FLASH_FLAG_PGERR      FLASH Program error flag
            - FLASH_FLAG_WRPERR     FLASH Write protected error flag
            - FLASH_FLAG_PVERR      FLASH Program Verify ERROR flag
            - FLASH_FLAG_EVERR      FLASH Erase Verify ERROR flag
            - FLASH_FLAG_ECC1ERR    FLASH 1 bit ECC ERROR flag
            - FLASH_FLAG_RDKEYERR   read key error flag
            - FLASH_FLAG_RDXKEYERR  xKEY match error flag
            - FLASH_FLAG_NRDXKEYEN  Not allowed to read RTPD_KEY enable flag
            - FLASH_FLAG_JSERR      JTAG/SRAM access JTAG_SEAL error flag
            - FLASH_FLAG_RTPKEYERR  read RTPD_KEY error flag
            - FLASH_FLAG_ECC2ERR    FLASH 2 bit ECC error flag
            - FLASH_FLAG_DECCRDF    XSPI/FEMC Decryption Configuration Completion Flag
            - FLASH_FLAG_DECCERR    XSPI/FEMC Decryption Configuration sequences error Flag
            - FLASH_FLAG_FWORDF     first word write completion flag
            - FLASH_FLAG_RPADDERR   row programmmer address error
            - FLASH_FLAG_BANKEXERR  BANK exchange error
            - FLASH_FLAG_BANKMODE   BANK mode
            - FLASH_FLAG_OBERR      FLASH Option Byte error flag
return bitstatus :
        - SET
        - RESET
void FLASH_ClearFlag(uint32_t FLASH_FLAG)Clears the FLASH’s pending flags.
Source comment
name   FLASH_ClearFlag
fun    Clears the FLASH's pending flags.
param  FLASH_FLAG :(The input parameters must be the following values)
            - FLASH_FLAG_EOP        FLASH End of Operation flag
            - FLASH_FLAG_PGERR      FLASH Program error flag
            - FLASH_FLAG_WRPERR     FLASH Write protected error flag
            - FLASH_FLAG_PVERR      FLASH Program Verify ERROR flag
            - FLASH_FLAG_EVERR      FLASH Erase Verify ERROR flag
            - FLASH_FLAG_ECC1ERR    FLASH 1 bit ECC ERROR flag
            - FLASH_FLAG_JSERR      JTAG/SRAM access JTAG_SEAL error flag
            - FLASH_FLAG_RTPKEYERR  read RTPD_KEY error flag
            - FLASH_FLAG_ECC2ERR    FLASH 2 bit ECC error flag
            - FLASH_FLAG_DECCRDF    XSPI/FEMC Decryption Configuration Completion Flag
            - FLASH_FLAG_DECCERR    XSPI/FEMC Decryption Configuration sequences error Flag
            - FLASH_FLAG_RPADDERR   row programmmer address error
            - FLASH_FLAG_BANKEXERR  BANK exchange error
return none
FLASH_STS FLASH_GetSTS(void)Returns the FLASH Status.
Source comment
name   FLASH_GetSTS
fun    Returns the FLASH Status.
param  none
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
FLASH_STS FLASH_WaitForLastOpt(uint32_t Timeout)Waits for a Flash operation to complete or a TIMEOUT to occur.
Source comment
name   FLASH_WaitForLastOpt
fun    Waits for a Flash operation to complete or a TIMEOUT to occur.
param  Timeout:(The input parameters must be the following values)
            - EraseTimeout
            - ProgramTimeout
            - RowProgramTimeout
return FLASH_STS :
            - FLASH_BUSY     FLASH is busy
            - FLASH_ERR_PG   FLASH programming error
            - FLASH_ERR_WRP  FLASH Write protected error
            - FLASH_EOP      FLASH End of Operation
            - FLASH_ERR_PV   Programmer Verification Error
            - FLASH_ERR_EV   Erase Verification Error
            - FLASH_ERR_RPADD   FLASH Row programmer address error
void CCM_EnWriteProtection(uint32_t CCM_Pages)Enables write protection CCM x page.
Source comment
name   CCM_EnWriteProtection
fun    Enables write protection CCM x page.
param  CCM_Pages:(The input parameters must be the following values)
            - Bit31 - Bit0 write-protects pages (31) - page (0)
return none
uint32_t CCM_GetWriteProtectionSTS(void)Returns the CCM Write Protection Option Bytes Register value.
Source comment
name   CCM_GetWriteProtectionSTS
fun    Returns the CCM Write Protection Option Bytes Register value.
param  none
return The CCM Write Protection  Option Bytes Register value :
            - Bit31 - Bit0 write-protects pages (31) - page (0)
void CCM_Earse_Unlock(void)Unlocks the CCM Erase Controller.
Source comment
name   CCM_ERASE_Unlock
fun    Unlocks the CCM Erase Controller.
param  none
return none

Use note: The declaration at line 376 of the header is CCM_Earse_Unlock, while the name field of the source comment reads CCM_ERASE_Unlock; the two differ.

void CCM_EarseEN(void)ENABLE CCM Erase.
Source comment
name   CCM_ERASE_EN
fun    ENABLE CCM Erase.
param  none
return none

Use note: The declaration at line 377 of the header is CCM_EarseEN, while the name field of the source comment reads CCM_ERASE_EN; the two differ.

FlagStatus CCM_EarseSTS(void)Get CCM Erase Status.
Source comment
name   CCM_EarseSTS
fun    Get CCM Erase Status.
param  none
return FlagStatus :
        - SET    CCM SRAM erase operation
        - RESET  No CCM SRAM erase operation
void CCM_ModeSet(FunctionalState Cmd)Enables or disables CCM mode.
Source comment
name   CCM_ModeSet
fun    Enables or disables CCM mode.
param  Cmd:(The input parameters must be the following values)
            - ENABLE
            - DISABLE
return none
void XSPI_DESRangeSet(uint32_t start_add,uint32_t end_add)XSPI Decryption address range setting.
Source comment
name   XSPI_DESRangeSet
fun    XSPI Decryption address range setting.
param  start_add:(The input parameters must be the following values)
            - It ranges from 0x90000000 to 0x9FFFFFFF
param  end_add:(The input parameters must be the following values)
            - It ranges from 0x90000000 to 0x9FFFFFFF
return none
void FEMC_DESRangeSet(uint32_t start_add,uint32_t end_add)FEMC Decryption address range setting.
Source comment
name   FEMC_DESRangeSet
fun    FEMC Decryption address range setting.
param  start_add:(The input parameters must be the following values)
            - It ranges from 0x60000000 to 0x8FFFFFFF
param  end_add:(The input parameters must be the following values)
            - It ranges from 0x60000000 to 0x8FFFFFFF
return none
void RTP_DESKeySet(uint32_t* DES_key)128bit RTPD decryption key setting.
Source comment
name   RTP_DESKeySet
fun    128bit RTPD decryption key setting.
param  DES_key:(The input parameters must be the following values)
            - A 128-bit key
return none
uint32_t GetRTP_DESKeyWnum(void)get RTPD_KEY Write Count.
Source comment
name   GetRTP_DESKeyWnum
fun    get RTPD_KEY Write Count.
param  none
return CNT:
            - RTPD_KEY write cnt
void Jtag_SealSet(FunctionalState Cmd)Enables or disables Jtag_Seal.
Source comment
name   Jtag_SealSet
fun    Enables or disables Jtag_Seal.
param  Cmd:(The input parameters must be the following values)
            - ENABLE
            - DISABLE
return none
void XSPI_FEMC_DESSet(FunctionalState Cmd)Enables or disables XSPI/FEMC decryption.
Source comment
name   XSPI_FEMC_DESSet
fun    Enables or disables XSPI/FEMC decryption.
param  Cmd:(The input parameters must be the following values)
            - ENABLE
            - DISABLE
return none
uint32_t Get_XFUID(void)get XSPI/FEMC configure UID.
Source comment
name   Get_XFUID
fun    get XSPI/FEMC configure UID.
param  none
return UID:
            - 0x01  BOOT user
            - 0x02  FLASH user1
            - 0x04  FLASH user2
            - 0x08  FLASH user3
            - 0x10  SRAM user
uint32_t Get_CCMUID(void)get CCM configure UID.
Source comment
name   Get_CCMUID
fun    get CCM configure UID.
param  none
return UID:
            - 0x01  BOOT user
            - 0x02  FLASH user1
            - 0x04  FLASH user2
            - 0x08  FLASH user3
            - 0x10  SRAM user

5.14.3 Demo descriptions

This section describes the 6 Flash examples: Flash_Program demonstrates page erase and double-word programming, Flash_Row_Program demonstrates row programming, OptionByte_Config demonstrates option-byte erase and program, SingleBankRemap demonstrates boot remapping in single-bank mode, DualBankSwap demonstrates the three dual-bank switch methods, and Run_In_CCM demonstrates executing function code from CCM SRAM.

5.14.3.1 DualBankSwap Dual-bank switching

Example directory: projects/n32h49x_EVAL/examples/Flash/DualBankSwap/

Initialize the UART and enable the HSI clock→Initialize the on-board LEDs→Check the current bank mode and require dual-bank mode→Read the boot bank and the remap bank from the option bytes→Restore the work-mode mark of the previous run→In the main loop switch banks in the Retry, Backup, and Reload ways by UART command→Turn on all LEDs before switching and then reset or remap

Item Source analysis
Function Demonstrates the three bank-switch methods in dual-bank mode: Retry switches by remapping, Backup switches by rewriting the option bytes and resetting, and Reload combines remapping with option-byte rewriting.
When the MCU runs on Bank1, LED1 blinks, and when it runs on Bank2, LED2 blinks;
after remapping, the other LED paired with the blinking one stays on.
Source files src/main.c: main, ConfigBootBank, SetModeMark, ClrModeMark, GetModeMark;
inc/main.h: OB_BUF_ADDRESS, MODE_MARK_ADDR, the three mode-mark macros, LED operation macros, and the ConfigBootBank declaration;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/, EWARM/: Keil and IAR projects.
Key configuration The example requires dual-bank mode (DBANK=1) and stays in a prompt loop in single-bank mode.
The option-byte buffer OB_BUF_ADDRESS is 0x40023000 and the work-mode mark MODE_MARK_ADDR is 0x40023080, both in backup SRAM.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path main first calls log_init, enables HSI and waits for it to stabilize, and initializes the LEDs;
it reads FLASH_FLAG_BANKMODE for the bank mode, then reads the option-byte boot bank and the RCC remap bank, and recovers the last work mode from two complementary marks;
the main loop polls USART1, where 0x55 goes to Retry, 0x66 to Backup, and 0x77 to Reload;
Retry and Reload call RCC_ConfigRemapMode and RCC_EnableRemap after SetModeMark, while Backup calls NVIC_SystemReset after ConfigBootBank.
Main APIs FLASH_GetFlagSTS, FLASH_Unlock, FLASH_EraseOB, Option_Bytes_Unlock, Option_Bytes_Lock, FLASH_ClearFlag, FLASH_WaitForLastOpt, FLASH_Lock
Verification After reset the UART prints the current bank and the boot address 0x08000000;
sending 0x55 shows the Retry remap, 0x66 shows Backup restarting from the other bank, and 0x77 shows the combined Reload switch;
on each successful switch the corresponding LED starts to blink.
Use note The boot address is always 0x08000000, and what switches is the actual code storage location.
Backup and Reload rewrite the option bytes, which is Flash programming, so HSI must already be on before running.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example switches the boot code between the two banks by remapping or by rewriting the option bytes, and passes the work mode across a reset with a mark in backup SRAM.

Data path: UART command -> SetModeMark writes MODE_MARK_ADDR -> RCC_ConfigRemapMode/RCC_EnableRemap or ConfigBootBank rewrites the option bytes -> NVIC_SystemReset resets -> GetModeMark restores the work mode

1. Enable HSI and check the bank mode. Flash programming or erasing requires HSI to be on, so the example enables HSI right after initialization; it then checks FLASH_FLAG_BANKMODE and, in single-bank mode, stays in a prompt loop and skips the rest of the switching logic.

src/main.csrc/main.c · main
    /* When performing Flash programming operations(write or erase), HSI must be enable*/
    RCC_EnableHsi(ENABLE);
    RCC_WaitHsiStable();
    
    /* User LED Init */
    Hardware_Board_Led_Init();
    
    /* Check current Bank mode, must be in dual Bank mode */
    if(FLASH_GetFlagSTS(FLASH_FLAG_BANKMODE) == SET)
    {
        log_info("\r\nFLASH is dual Bank mode!\r\n");
    }
    else
    {
        log_info("\r\nFLASH is single Bank mode!\r\n");
        log_info("This demo can not be used!\r\n");
        while(1)
        {
            /* Dual Bank swap demo is only used for dual Bank mode */
        }
    }

2. Retry switches by remapping. After receiving 0x55, the example chooses the remap target from the current work bank, first writes the work-mode mark, then turns on all LEDs, and finally configures and starts the remap, so the code storage location changes while the boot address stays the same.

src/main.csrc/main.c · main
        if(UartCmd == 0x55U) /* Retry */
        {
            if(FLASH_BANK2 == WorkBankNum)
            {
                Value_temp = RCC_REMAP_BFLASH;
                log_info("Remap to Bank1!\r\n");
            }
            else
            {
                Value_temp = RCC_REMAP_AFLASH;
                log_info("Remap to Bank2!\r\n");
            }
            
            /* Set the mark of work mode */
            SetModeMark(RETRY_MARK);
            
            /* Turn on all LED before remap */
            ALL_BANK_LED_ON;
            systick_delay_ms(5);
            
            /* Config remap bank and remap */
            RCC_ConfigRemapMode(Value_temp);
            RCC_EnableRemap();
        }

3. Switch the boot bank by rewriting the option bytes directly. ConfigBootBank first reads the current option bytes into backup SRAM, modifies the boot-bank field of USER2, and then programs them double-word by double-word; it only proceeds to the next group when the previous program returns FLASH_EOP.

src/main.csrc/main.c · ConfigBootBank
    /* Erase */
    ConfigSts = FLASH_EraseOB();
    
    /* Erase success, write the new value of option byte */
    if(FLASH_EOP == ConfigSts)
    {
        /* Unlock option byte */
        Option_Bytes_Unlock();
        
        /* Clears the FLASH's pending flags */
        FLASH_ClearFlag(FLASH_STS_CLRFLAG);
        
        /* Enables the Option Bytes Programming operation */
        FLASH->CTRL |= CTRL_Set_OPTPG;
        
        /* Option byte must be programming in the unit of double-word */
        /* Programming the 1st double word at 0x1FFF_E000 */
        OBT->RDP2_RDP1          = pBuf[0];
        OBT->CCMSRAM_RST_DBANK  = pBuf[1];
        
        /* Wait for the programming operation to complete */
        ConfigSts = FLASH_WaitForLastOpt(ProgramTimeout);
        
        /* Disable the Option Bytes Programming operation */
        FLASH->CTRL &= CTRL_Reset_OPTPG;
    }

4. Pass the work mode across a reset with complementary marks. The work mode is written to backup SRAM at MODE_MARK_ADDR as the original value and its bitwise complement; on read, when the two are not complementary the mark is treated as invalid, and the last switch method is recovered after reset.

src/main.csrc/main.c · SetModeMark
static void SetModeMark(uint32_t mark)
{
    uint32_t *pMark;

    pMark = (uint32_t *)MODE_MARK_ADDR;
    
    pMark[0]    = mark;
    pMark[1]    = (~mark);
}
src/main.csrc/main.c · GetModeMark
static uint32_t GetModeMark(void)
{
    uint32_t *pMark;
    uint32_t tMode;

    pMark = (uint32_t *)MODE_MARK_ADDR;
    
    tMode = pMark[0];
    if(tMode != (~pMark[1]) )
    {
        tMode = 0xFFFFFFFFU;
    }
    
    return tMode;
}

Corresponding source files: src/main.c, inc/main.h

5.14.3.2 Flash_Program Page erase and double-word programming

Example directory: projects/n32h49x_EVAL/examples/Flash/Flash_Program/

Initialize the UART→Unlock the Flash program/erase controller→Erase the page at the start address→Write a whole page of data stepping by double words→Lock the controller→Read back word by word and compare the result

Item Source analysis
Function Demonstrates erasure and double-word programming of a main-memory page.
After erasing the page starting at 0x08008000, it writes fixed data over the whole page in 8-byte steps, locks the controller, reads back word by word for comparison, and prints the test result.
Source files src/main.c: main and the page-size and address macros FLASH_PAGE_SIZE, FLASH_WRITE_START_ADDR, FLASH_WRITE_END_ADDR;
inc/main.h: common header;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/, EWARM/: Keil and IAR projects with project name Flash_Program_Proj.
Key configuration Page size FLASH_PAGE_SIZE is 0x2000 (8KB per page in dual-bank mode);
the write range is 0x08008000 to 0x08010000;
the write data is fixed at 0xCDEF89AB.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path main first calls log_init and then FLASH_Unlock;
it erases the page at the start address with FLASH_EraseOnePage, and stops at an error prompt when the return is not FLASH_EOP;
it writes the same double word over the whole page in 8-byte steps, again stopping at an error prompt when the return is not FLASH_EOP;
after FLASH_Lock it reads back in 4-byte steps for comparison and prints the end of the test when they agree.
Main APIs FLASH_Unlock, FLASH_EraseOnePage, FLASH_ProgramdoubleWord, FLASH_Lock
Verification After reset the UART prints Flash Program Test Start;
when erase, program and read-back comparison all pass it prints Flash Program Test End;
when any step fails it stops at the corresponding error prompt.
Use note Writing supports only double words, so the program loop steps by 8 bytes while the read-back steps by 4 bytes.
Erase before writing, and this example erases the page starting at 0x08008000.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example erases a whole page, programs it double-word by double-word, and then reads it back word by word to verify data consistency.

Data path: FLASH_Unlock -> FLASH_EraseOnePage(0x08008000) -> FLASH_ProgramdoubleWord writes a whole page in 8-byte steps -> FLASH_Lock -> read back word by word and compare -> print the result over UART

1. Unlock and erase the start page. The example unlocks the program/erase controller and then erases the page at the start address of the write range; when the erase result is not FLASH_EOP it stops at an error prompt and does not program.

src/main.csrc/main.c · main
    /* Unlocks the FLASH Program Erase Controller */
    FLASH_Unlock();

    /* Erase */
    if (FLASH_EOP != FLASH_EraseOnePage(FLASH_WRITE_START_ADDR))
    {
        while(1)
        {
            printf("Flash EraseOnePage Error. Please Deal With This Error Promptly\r\n");
        }
    }

2. Write a whole page stepping by double words. The loop steps by 8 bytes and writes the data 0xCDEF89AB as two 32-bit words each time, matching the alignment requirement of double-word programming; it stops at an error prompt when the return is not FLASH_EOP.

src/main.csrc/main.c · main
    /* Program */
    for (Counter_Num = 0; Counter_Num < FLASH_PAGE_SIZE; Counter_Num += 8)
    {
        if (FLASH_EOP != FLASH_ProgramdoubleWord(FLASH_WRITE_START_ADDR + Counter_Num, Erase_Data,Erase_Data))
        {
            while(1)
            {
                log_info("Flash ProgramWord Error. Please Deal With This Error Promptly\r\n");
            }
        }
    }

3. Lock and read back word by word. After programming it locks the controller and then reads back in 4-byte steps; it prints a test failure when a word differs from the written data, otherwise it continues and prints the end of the test.

src/main.csrc/main.c · main
    /* Locks the FLASH Program Erase Controller */
    FLASH_Lock();

    /* Check */
    for (Counter_Num = 0; Counter_Num < FLASH_PAGE_SIZE; Counter_Num += 4)
    {
        if (Erase_Data != (*(__IO uint32_t*)(FLASH_WRITE_START_ADDR + Counter_Num)))
        {
            printf("Flash Program Test Failed\r\n");
            break;
        }
    }

Corresponding source files: src/main.c

5.14.3.3 Flash_Row_Program Row programming

Example directory: projects/n32h49x_EVAL/examples/Flash/Flash_Row_Program/

Initialize the UART→Unlock the Flash program/erase controller→Erase the start page→Enable the row programmer and select the main memory→Program 16 words continuously stepping by 64 bytes→Lock the controller→Read back word by word and print the result

Item Source analysis
Function Demonstrates the continuous write capability of the row programmer.
After erasing a page it enables the row programmer, writes 16 words at a time in 64-byte steps, and after locking reads back word by word for comparison and prints the result.
Source files src/main.c: main, the address macros, and the 16-element write buffer Erase_Data;
inc/main.h: common header;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/, EWARM/: Keil and IAR projects.
Key configuration The write buffer Erase_Data[16] is all 0xCDEF89AB;
FLASH_RowProgramSet(ENABLE) enables the row programmer and FLASH_RowProgramAreaSet(DISABLE) selects the main memory;
the row-program length parameter is 0x10, that is 16 words.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path The same unlock and page-erase flow as Flash_Program;
after erasing it enables the row programmer and selects the main memory;
it calls FLASH_RowProgram in 64-byte steps, writing 16 words each time;
after locking it reads back in 4-byte steps and compares the first element of the buffer.
Main APIs FLASH_Unlock, FLASH_EraseOnePage, FLASH_RowProgramSet, FLASH_RowProgramAreaSet, FLASH_RowProgram, FLASH_Lock
Verification After reset the UART prints Flash Row Program Test Start;
when the read-back comparison all passes it prints Flash Program Test End;
on failure it prints Flash Program Test Failed.
Use note Row programming writes 2 to 16 words at a time and cannot span 512 bytes, so this example writes 16 words with a 64-byte step.
The program address must be 8-byte aligned and the word count must be even.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example uses the row programmer to write several consecutive words at once, shortening the programming time of a whole page.

Data path: FLASH_Unlock -> FLASH_EraseOnePage -> FLASH_RowProgramSet(ENABLE)/FLASH_RowProgramAreaSet(DISABLE) -> FLASH_RowProgram writes 16 words in 64-byte steps -> FLASH_Lock

1. Enable the row programmer and select the main memory. After the erase, the example enables the row programmer and then sets the operation area to the main memory; FLASH_RowProgramAreaSet(DISABLE) corresponds to programming in the main memory rather than the system memory.

src/main.csrc/main.c · main
    /* Flash row programmer configure*/
    FLASH_RowProgramSet(ENABLE);
    FLASH_RowProgramAreaSet(DISABLE);

2. Program continuously in 64-byte steps. The loop steps by 64 bytes and calls FLASH_RowProgram to write 16 words each time; a single write does not span 512 bytes, and it stops at an error prompt when the return is not FLASH_EOP.

src/main.csrc/main.c · main
    /*Row Program */
    for (Counter_Num = 0; Counter_Num < FLASH_PAGE_SIZE; Counter_Num += 64)
    {
        if (FLASH_EOP != FLASH_RowProgram(FLASH_WRITE_START_ADDR + Counter_Num,0x10U, Erase_Data))
        {
            while(1)
            {
                log_info("Flash ProgramWord Error. Please Deal With This Error Promptly\r\n");
            }
        }
    }

3. Lock and read back for comparison. After locking the controller, the example reads back in 4-byte steps and compares with the first element of the buffer; on mismatch it prints a test failure, otherwise it continues and prints the end of the test.

src/main.csrc/main.c · main
    /* Locks the FLASH Program Erase Controller */
    FLASH_Lock();

    /* Check */
    for (Counter_Num = 0; Counter_Num < FLASH_PAGE_SIZE; Counter_Num += 4)
    {
        if (Erase_Data[0] != (*(__IO uint32_t*)(FLASH_WRITE_START_ADDR + Counter_Num)))
        {
            printf("Flash Program Test Failed\r\n");
            break;
        }
    }

Corresponding source files: src/main.c

5.14.3.4 OptionByte_Config Option-byte configuration

Example directory: projects/n32h49x_EVAL/examples/Flash/OptionByte_Config/

Initialize the UART→Unlock the Flash and option-byte controllers→Erase the option bytes→Program read protection and bank mode, USER/USER2, write protection, data bytes, and SRAM ECC in turn→Lock both controllers→Wait for the UART to send 0x55 and restore the defaults

Item Source analysis
Function Demonstrates erasure and programming of the option bytes.
After reset it erases the option bytes and configures read protection, bank mode, USER/USER2, write protection, data bytes, and SRAM ECC in turn, then waits for the UART to send 0x55 to restore the option bytes to their defaults.
Source files src/main.c: main, containing both the default-configuration flow and the 0x55 restore flow;
inc/main.h: common header;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/, EWARM/: Keil and IAR projects.
Key configuration The defaults are dual-bank mode, CCMSRAM reset without erase, software IWDG, and BOR threshold 1.6V;
write protection is configured as FLASH_WRP_NUM16 (single-bank pages 32 to 33, dual-bank pages 64 to 67);
the option-byte data is written as 0x55, 0x66, 0x77, 0xAA;
SRAM2 and SRAM3 ECC are enabled.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path main first calls log_init, then FLASH_Unlock and Option_Bytes_Unlock;
it erases the option bytes with FLASH_EraseOB, and after FLASH_EOP it calls FLASH_ProgramOB_RRDC, FLASH_ProgramOB_U1U2, FLASH_EnWriteProtection, FLASH_ProgramOB_Data, and FLASH_ProgramOB_SRAMECC in turn;
each step uses FLASH_EOP to continue, and both controllers are locked after all steps complete;
the main loop waits for USART1 to receive 0x55 and then reprograms a group of option bytes with the default parameters.
Main APIs FLASH_Unlock, Option_Bytes_Unlock, FLASH_EraseOB, FLASH_ProgramOB_RRDC, FLASH_ProgramOB_U1U2, FLASH_EnWriteProtection, FLASH_ProgramOB_Data, FLASH_ProgramOB_SRAMECC, FLASH_Lock, Option_Bytes_Lock
Verification After reset the UART prints Option Byte configure Test start;
when all five program steps succeed it prints Option Byte configure OK;
after sending 0x55 it prints whether the restore to defaults succeeded or failed.
Use note Option-byte programming works in double words and must erase before writing, and both the Flash and option-byte controllers must be unlocked first.
Changes such as read protection L2 and the bank-mode switch fully take effect only after the Flash is re-flashed.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example demonstrates erasing the whole option-byte group and programming it item by item, and how to restore the option bytes to their defaults.

Data path: FLASH_Unlock/Option_Bytes_Unlock -> FLASH_EraseOB -> the five program functions such as FLASH_ProgramOB_RRDC -> FLASH_Lock/Option_Bytes_Lock -> UART 0x55 triggers the restore to defaults

1. Erase the option bytes and program them item by item. The example unlocks both controllers and erases the option bytes; after a successful erase it programs USER/USER2 in order, and each step uses the returned status to decide whether to continue.

src/main.csrc/main.c · main
    /* Unlocks the FLASH Program Erase Controller */
    FLASH_Unlock();
    /* Unlocks the Option Byte Program Erase Controller */
    Option_Bytes_Unlock();
    /*  Erase Option Byte page */
    state_value = FLASH_EraseOB();
    
    if(state_value == FLASH_EOP)
    {
src/main.csrc/main.c · main
        if(state_value == FLASH_EOP)
        {
            /* Configure option bytes RDP2, user2 and user3 */
            state_value = FLASH_ProgramOB_U1U2(FLASH_OB_IWDG_SOFTWARE,FLASH_OB_STOP_NORST,FLASH_OB_STDBY_NORST,\
                                                FLASH_OB_IWDG_STOP_NOFRZ,FLASH_OB_IWDG_STDBY_NOFRZ,FLASH_OB_IWDG_SLEEP_NOFRZ,\
                                                FLASH_OB2_NBOOT0_SET,FLASH_OB2_NBOOT1_SET,FLASH_OB2_NSWBOOT0_SET,\
                                                FLASH_OB2_FLASHBOOT_SET,FLASH_OB2_DAC_SET,BOR_LEVEL_1_6V);
        }

2. Program write protection, data bytes, and SRAM ECC. The next three steps at the same level configure the write-protect page, the option-byte data, and the ECC enable bits of SRAM2 and SRAM3; they are written like the previous step and enter an empty branch on failure.

src/main.csrc/main.c · main
        if(state_value == FLASH_EOP)
        {
            /* Enable writing protection Single Bank: page 32 to 33, Dual Banke: page 64  to 67 */
            state_value = FLASH_EnWriteProtection(FLASH_WRP_NUM16);
        }
        else
        {
            /* no process*/
        }
        
        if(state_value == FLASH_EOP)
        {
            /* Configure option byte datax */
            state_value = FLASH_ProgramOB_Data(0x55,0x66,0x77,0xAA);
src/main.csrc/main.c · main
        if(state_value == FLASH_EOP)
        {
            /* Configure option byte CCMSRAM reset without erasing */
            state_value = FLASH_ProgramOB_SRAMECC(SRAM2_ECC_ENABLE,SRAM3_ECC_ENABLE);
        }
        else
        {
            /* no process*/
        }

3. Restore the defaults with UART 0x55. After the main loop receives 0x55 it repeats the unlock and erase flow, then rewrites read protection and the bank mode with the default parameters, thus restoring the previously changed option bytes to their defaults.

src/main.csrc/main.c · main
        UartCmd = USART_ReceiveData(USART1);
        if(UartCmd == 0x55)
        {
            /* Unlocks the FLASH Program Erase Controller */
            FLASH_Unlock();
            /* Unlocks the Option Byte Program Erase Controller */
            Option_Bytes_Unlock();
            /*  Erase Option Byte page */
            state_value = FLASH_EraseOB();

Corresponding source files: src/main.c

5.14.3.5 Run_In_CCM Running code in CCM SRAM

Example directory: projects/n32h49x_EVAL/examples/Flash/Run_In_CCM/

Initialize the UART→Mirror the boot code already copied into CCM SRAM to a plain-SRAM backup→Initialize CCM SRAM with a one-key init that zeroes it and forms the ECC bits→Write the backup bytes back to CCM SRAM→Print the three function addresses and confirm they fall in the CCM SRAM range→Run the three-level nested call chain and check the return value

Item Source analysis
Function Demonstrates how to keep function code in Flash, copy it to CCM SRAM at runtime, and execute it there.
The example uses a three-level nested call chain, prints the execution addresses of three functions to confirm they are in CCM SRAM, and checks that the call chain returns 448.
Source files src/main.c: main, CCM_SRAM_Init, CCM_SRAM_SaveCode, CCM_SRAM_RestoreCode, and the three marked CCM functions;
inc/main.h: common header;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/ (with the custom scatter file Run_In_CCM.sct) and EWARM/ (with the custom ICF file Run_In_CCM.icf): Keil and IAR projects.
Key configuration The CCM SRAM range is 0x20070000 to 0x2007FFFF, 64KB in size;
the backup buffer ccm_backup holds 256 words;
the __CCM_FUNC macro places functions in the CCM section per toolchain (Keil ccmram, IAR CCM_CODE), and the custom linker script sets the functions’ load address in Flash and execution address in CCM SRAM.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path main first calls log_init;
it calls CCM_SRAM_SaveCode to mirror the current CCM SRAM contents into ccm_backup;
it calls CCM_SRAM_Init, which writes the start address, configures the initialization range and value, starts the one-key init and waits for completion, and then calls CCM_ModeSet;
CCM_SRAM_RestoreCode writes the backup back;
it takes the three function addresses to check whether they fall in the CCM SRAM range, and finally calls CCM_WeightedSumOfSquares(5) and checks the return of 448.
Main APIs CCM_ModeSet (the CCM SRAM one-key init is configured directly through RCC->SRAMCFG1 to SRAMCFG4)
Verification The UART prints CCM Function Code Saved, CCM SRAM Initialized, and CCM Function Code Restored in turn;
when all three function addresses fall in the CCM SRAM range it prints [PASS];
when the call chain returns 448 it prints Run_In_CCM Test Passed.
Use note CCM SRAM enables ECC by default, so the ECC bits must be valid before reading;
the one-key init clears the whole CCM SRAM, including the function code the boot code has already copied, so it must be written back after initialization.
The Keil project must use Run_In_CCM.sct and the IAR project must use Run_In_CCM.icf.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example shows how to place functions in CCM SRAM for execution and how to use a backup buffer to avoid the one-key init clearing the code.

Data path: CCM_SRAM_SaveCode mirrors CCM SRAM -> CCM_SRAM_Init runs the one-key init and CCM_ModeSet -> CCM_SRAM_RestoreCode writes back -> check the function addresses are in CCM SRAM -> CCM_WeightedSumOfSquares returns 448

1. Place functions in the CCM section with a macro. The example defines __CCM_FUNC per toolchain, using the ccmram section for Keil and the custom CCM_CODE section for IAR; a marked function still has its load address in Flash, and the linker script sets its execution address in CCM SRAM.

src/main.csrc/main.c
#if defined(__CC_ARM) || defined(__ARMCC_VERSION)
#define __CCM_FUNC  __attribute__((section("ccmram")))
#elif defined(__ICCARM__)
#define __CCM_FUNC  _Pragma("location=\"CCM_CODE\"")
#elif defined(__GNUC__)
#define __CCM_FUNC  __attribute__((section(".ccmram")))
#else
#define __CCM_FUNC
#endif

2. One-key initialize CCM SRAM. CCM_SRAM_Init first writes an initialization value to the start address, then configures the initialization range and value, starts the one-key init and waits for the completion flag, and finally clears the enable bit and turns on CCM mode.

src/main.csrc/main.c · CCM_SRAM_Init
    *(__IO uint32_t *)CCM_SRAM_BASE = 0x00000000U;

    /* Step 1: Configure initialization range
       End address must differ from start address */
    RCC->SRAMCFG3 = (uint32_t)CCM_SRAM_BASE;
    RCC->SRAMCFG4 = (uint32_t)(CCM_SRAM_BASE + CCM_SRAM_SIZE - 4U);

    /* Step 2: Configure initialization value */
    RCC->SRAMCFG2 = 0x00000000U;

    /* Step 3: Start one-key initialization */
    RCC->SRAMCFG1 |= RCC_SRAMCFG1_SRINIEN;

    /* Step 4: Wait for initialization complete */
    while (!(RCC->SRAMCFG1 & RCC_SRAMCFG1_SRINIF))
    {
    }

    /* Clear initialization enable */
    RCC->SRAMCFG1 &= ~RCC_SRAMCFG1_SRINIEN;
    
    /* Enable CCM mode */
    CCM_ModeSet(ENABLE);

3. Save the code, write it back, and check the execution addresses. The one-key init overwrites the function bytes the boot code has already copied to CCM SRAM, so the example first mirrors those words to plain SRAM and writes them back after initialization; it then takes the three function addresses and checks whether they fall in the CCM SRAM range.

src/main.csrc/main.c · CCM_SRAM_SaveCode
    volatile uint32_t *src = (volatile uint32_t *)CCM_SRAM_BASE;
    uint32_t i;

    for (i = 0U; i < CCM_BACKUP_WORDS; i++)
    {
        ccm_backup[i] = src[i];
    }
src/main.csrc/main.c · main
    addr_square   = (uint32_t)CCM_Square              & ~1U;
    addr_sum      = (uint32_t)CCM_SumOfSquares         & ~1U;
    addr_weighted = (uint32_t)CCM_WeightedSumOfSquares & ~1U;

    printf("CCM_Square Address              : 0x%08X\r\n", (unsigned int)addr_square);
    printf("CCM_SumOfSquares Address        : 0x%08X\r\n", (unsigned int)addr_sum);
    printf("CCM_WeightedSumOfSquares Address: 0x%08X\r\n", (unsigned int)addr_weighted);
    printf("CCM SRAM Range: 0x%08X ~ 0x%08X\r\n",
           (unsigned int)CCM_SRAM_BASE, (unsigned int)CCM_SRAM_END);

    if ((addr_square   >= CCM_SRAM_BASE) && (addr_square   <= CCM_SRAM_END) &&
        (addr_sum      >= CCM_SRAM_BASE) && (addr_sum      <= CCM_SRAM_END) &&
        (addr_weighted >= CCM_SRAM_BASE) && (addr_weighted <= CCM_SRAM_END))
    {
        printf("All Functions In CCM SRAM [PASS]\r\n");
    }
    else
    {
        printf("Function NOT In CCM SRAM [FAIL]\r\n");
        while (1)
        {
        }
    }

Corresponding source files: src/main.c

5.14.3.6 SingleBankRemap Single-bank boot remapping

Example directory: projects/n32h49x_EVAL/examples/Flash/SingleBankRemap/

Initialize the UART→Read and print the current bank mode→Read the boot-remap status→Wait for a UART command→Rewrite the boot-area option bytes and reset, or remap directly→Boot from the forward or back half of the main memory

Item Source analysis
Function Demonstrates boot remapping in single-bank mode (DBANK=0).
The example reads the current bank mode and boot-remap status and, through a UART command, rewrites the boot-area option bytes or remaps directly so that the system boots from the forward or back half of the main memory.
Source files src/main.c: main and the boot-enable macro FLASH_BOOTENABLE;
inc/main.h: common header;
src/n32h49x_it.c, inc/n32h49x_it.h: interrupt service routines;
readme.txt: features, environment, and usage;
MDK-ARM/, EWARM/: Keil and IAR projects.
Key configuration The boot-enable flag FLASH_BOOTENABLE is 0x00080000, and the boot area is judged through the system-memory address 0x1FFFE010;
the boot area is set by the FLASH_OB2_FLASHBOOT bit of USER2 in the option bytes;
the remap status is read through the RCC_BOOTREMAP_REMAPSEL field of RCC->BOOTREMAP.
System clock 240 MHz, UART USART1 TX PA9 and RX PA10 at 115200 baud.
Program and data path main first calls log_init;
it uses FLASH_GetFlagSTS(FLASH_FLAG_BANKMODE) to print the current bank mode, then reads RCC->BOOTREMAP and 0x1FFFE010 to judge the current boot area;
the main loop polls USART1: 0x55 configures the forward half as the boot area and 0x66 the back half, and both rewrite the option bytes and then reset;
0x77 and 0x88 only remap the forward and back halves.
Main APIs FLASH_GetFlagSTS, FLASH_Unlock, FLASH_EraseOB, FLASH_ProgramOB_RRDC, FLASH_ProgramOB_U1U2
Verification After reset the UART prints the current bank mode and boot area;
after sending 0x55 or 0x66 the system resets and boots from the corresponding half;
after sending 0x77 or 0x88 it remaps directly and boots from the corresponding half.
Use note In single-bank mode the main memory is split into a forward and a back half, and the boot address is always 0x08000000.
After rewriting the boot-area option bytes a system reset is required, which the example does with NVIC_SystemReset.
Development environment is KEIL MDK-ARM V5.34 or IAR EWARM 8.50.1.
Core-code walkthrough and porting

The example reads the boot-area source and switches the boot area to the other half of the main memory through the option bytes or an RCC remap.

Data path: read FLASH_FLAG_BANKMODE and RCC->BOOTREMAP/0x1FFFE010 -> UART command -> FLASH_ProgramOB_U1U2 changes the boot bit and resets, or RCC_ConfigRemapMode/RCC_EnableRemap remaps

1. Read the bank mode and boot area. The example first prints the bank mode, then reads the remap register; when remapping is not enabled it reads the boot-enable bit in the system memory instead, and from that judges whether the system boots from the forward or the back half of the main memory.

src/main.csrc/main.c · main
    /* Show bank mode */
    if(FLASH_GetFlagSTS(FLASH_FLAG_BANKMODE) == SET)
    {
        log_info("FLASH is dual bank mode!\r\n");
    }
    else
    {
        log_info("FLASH is single bank mode!\r\n");
    }

    Value_temp = RCC->BOOTREMAP  & RCC_BOOTREMAP_REMAPSEL;
    if(Value_temp == RCC_REMAP_BFLASH)
    {
        FlashRemap = RCC_REMAP_BFLASH;
        log_info("Flash starts from the forward half, with startup address 0x08000000!\r\n");
    }
    else if(Value_temp == RCC_REMAP_AFLASH)
    {
        FlashRemap = RCC_REMAP_AFLASH;
        log_info("Flash starts from the back half, with startup address 0x08000000!\r\n");
    }
    else
    {
        log_info("No boot remap!\r\n");
        if(((*(uint32_t*)(0x1FFFE010)) & FLASH_BOOTENABLE) ==  FLASH_BOOTENABLE)
        {
            FlashRemap = RCC_REMAP_BFLASH;
            printf("System start from the forward half,with startup address 0x08000000!\r\n");
        }
        else
        {
            FlashRemap = RCC_REMAP_AFLASH;
            printf("System start from the back half,with startup address 0x08000000!\r\n");
        }
    }

2. Rewrite the boot-area option bytes and reset. When the boot area must be changed persistently, the example unlocks and erases the option bytes, first configures single-bank mode, then writes the target half through the boot bit of USER2, and finally calls NVIC_SystemReset.

src/main.csrc/main.c · main
        if(UartCmd == 0xDD) /* Modify OB */
        {
            FLASH_Unlock();
            FLASH_EraseOB();
            
            /* Configure FLASH to Single BANK mode */
            FLASH_ProgramOB_RRDC(FLASH_OB_RDP1_DISABLE,FLASH_OB_RDP2_DISABLE,FLASH_SINGLE_BANK,CCMSRAM_RST_NERASE);
            
            /* Configure FLASH BANK1 startup */
            FLASH_ProgramOB_U1U2(FLASH_OB_IWDG_SOFTWARE,FLASH_OB_STOP_NORST,FLASH_OB_STDBY_NORST,FLASH_OB_IWDG_STOP_NOFRZ,\
                                 FLASH_OB_IWDG_STDBY_NOFRZ,FLASH_OB_IWDG_SLEEP_NOFRZ,FLASH_OB2_NBOOT0_SET,FLASH_OB2_NBOOT1_SET,\
                                 FLASH_OB2_NSWBOOT0_SET,Value_temp,FLASH_OB2_DAC_SET, BOR_LEVEL_1_6V);
            
            log_info("System reset !\r\n");
            NVIC_SystemReset();
        }

3. Remap the boot area directly. When the option bytes need not be rewritten, the example only calls RCC_ConfigRemapMode and RCC_EnableRemap to switch the boot mapping immediately, without a reset.

src/main.csrc/main.c · main
        else if(UartCmd == 0xEE)    /* Remap */
        {
            RCC_ConfigRemapMode(Value_temp);
            RCC_EnableRemap();
        }

Corresponding source files: src/main.c

5.14.4 Notes and troubleshooting

Scenario Check & action Source
Clock condition for program/erase HSI must be enabled while performing Flash programming (write or erase);
all Flash operations are aborted in low-power modes.
User manual
Write granularity and erase unit Flash writes only support 64-bit double words;
writing a half word during programming causes a bus error;
erase before write, and the minimum erase unit is one 8KB page in dual-bank mode or one 16KB page in single-bank mode.
User manual
Access restrictions while BUSY While FLASH_STS.BUSY is 1, no write to any Flash register is allowed, and the same Flash cannot be read and written at the same time. User manual
Page-erase address alignment In single-bank mode Page_Address must be a multiple of 0x4000 (16KB per page);
in dual-bank mode it must be a multiple of 0x2000 (8KB per page).
User manual
Bank selection for mass erase With DBANK=0 (single bank), setting only MER1 or MER2 does not perform a mass erase. User manual
Row-program address span Row programming cannot span 512 bytes;
the program address must match the start address and word length of the row program.
User manual
Dual-bank concurrent access Dual-bank mode (DBANK=1) allows reading one bank while the other is erased or programmed;
two simultaneous writes are not allowed;
the option bytes and BANK1 sit in the same Flash and cannot be operated at the same time.
User manual
Option-byte unlock Unlock both Flash and the option bytes before programming or erasing them (FLASH_OPTKEY receives KEY1 0x45670123 and KEY2 0xCDEF89AB);
when OPTWE=0 the option bytes are locked.
User manual
Re-flash after bank-mode switch After switching the bank mode through the option bytes, the main-memory structure changes and the Flash must be re-flashed. User manual
Write-protection take effect After configuring write protection through WRP, a system reset is required for it to take effect;
programming or erasing a protected page returns a protection error flag.
User manual
Read-out protection L1 With read-out protection L1 enabled, all main-memory pages cannot be written or erased in debug mode or when booting from internal SRAM, except by a mass erase. User manual
Wait states and prefetch The read wait state must increase with the AHB clock (0 up to 48 MHz, 1 up to 96 MHz, 2 up to 144 MHz, 3 up to 192 MHz, 4 up to 240 MHz);
enabling the prefetch buffer improves efficiency when the wait state is nonzero.
User manual
Nations Technologies DevKit Docs

Datasheets, SDK, driver APIs and demo guides for Nations Technologies MCU development kits, organized by chip series.

© 2026 Nations Technologies Inc. All rights reserved.粤ICP备11069485号This site uses cookie-free anonymous analytics.