code-stm32读写FLASH

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了code-stm32读写FLASH相关的知识,希望对你有一定的参考价值。


#define FLASH_TYPEERASE_PAGES   ( (uint32_t) 0x00)      /*!<Pages erase only*/
#define FLASH_TYPEERASE_MASSERASE ( (uint32_t) 0x02) /*!<Flash mass erase activation*/
#define FLASH_BANK_1 ( (uint32_t) 0) /*!< Bank 1 */
#define FLASH_TYPEPROGRAM_HALFWORD ( (uint32_t) 0x01) /*!<Program a half-word (16-bit) at a specified address.*/

u16 u8ConvertU16( u8 a, u8 b )

u16 res = a << 8 | b;
return(res);



void erasePage( u32 pageStartAddress, u32 pageNum )

FLASH_EraseInitTypeDef eraseInit;
u32 error;
eraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
/* eraseInit.Banks = FLASH_BANK_1; */
eraseInit.NbPages = pageNum;
eraseInit.PageAddress = pageStartAddress;
if ( HAL_FLASHEx_Erase( &eraseInit, &error ) == HAL_OK )





u32 writeFlash( u8 *pSourceData, u32 targetAddress, u32 len )

HAL_FLASH_Unlock();
u32 writeData;
for ( u32 i = 0; i < len; i = i + 2 )

if ( targetAddress % 1024 == 0 )

erasePage( targetAddress, 1 );

writeData = u8ConvertU16( pSourceData[i + 1], pSourceData[i] );
if ( HAL_FLASH_Program( FLASH_TYPEPROGRAM_HALFWORD, targetAddress, writeData ) != HAL_OK )


targetAddress += 2;

HAL_FLASH_Lock();
return(targetAddress);



u32 writeU16ToFlash( u16* pSourceData, u32 targetAddress, u32 len )

HAL_FLASH_Unlock();
u32 writeData;
for ( u32 i = 0; i < len; i = i + 2 )

if ( targetAddress % 1024 == 0 )

erasePage( targetAddress, 1 );

writeData = (*pSourceData) & 0xffff;
if ( HAL_FLASH_Program( FLASH_TYPEPROGRAM_HALFWORD, targetAddress, writeData ) != HAL_OK )


targetAddress += 2;

HAL_FLASH_Lock();
return(targetAddress);




示例:


#define USER_DATA_BASE 0x800A000

void setLevelValue( u8 level, u8* u8Arr )

u8 page[1024] = 0 ;
u8 i = 0;

/* 拷贝值 */
for ( i = 0; i < 16; i++ )

page[i] = *(u32 *) (USER_DATA_BASE + i) & 0xff;


erasePage( USER_DATA_BASE, 1 );

writeFlash( page, USER_DATA_BASE, 16 );

__set_FAULTMASK( 1 );
NVIC_SystemReset();


以上是关于code-stm32读写FLASH的主要内容,如果未能解决你的问题,请参考以下文章

基于STM32的Flash读写详解

STM32学习笔记(16)——(SPI续)读写串行Flash

STM32CubeMX学习笔记(51)——读写内部Flash

STM32CubeMX学习笔记(51)——读写内部Flash

STM32F10x_SPI(硬件接口 + 软件模拟)读写Flash(25Q16)

STM32(十三)SPI-读写串行flash