STM32CubeMX开发之路—8Flash读写
读写一个数据的实例:
https://blog.csdn.net/weixin_41294615/article/details/87610039
国外老哥的程序:
https://controllerstech.com/flash-programming-in-stm32/
直接贴代码了,说明都在代码里:
下面是C文件:
//下面这些include 文件用的时候都包含进去;
#include "flash_read_write.h"
#include "stm32f1xx_hal.h"
#include "stdio.h"
#include "string.h"
//这个地址是stm32f103c8t6的最后一页的首地址
uint32_t addr = 0x08007000;
/*FLASH写入程序*/
uint32_t Flash_Write_Data (uint32_t StartPageAddress, uint32_t * DATA_32)
{
//声明结构体
static FLASH_EraseInitTypeDef EraseInitStruct;
//错误处理
uint32_t PAGEError;
int sofar=0;//计数作用
//计算要写入的数据的长度,正确的代码被我注释掉了,strlen总是报错,烦得很,直接把我要写的数据的长度赋值了,有能力的同学自己研究一下这句代码;
// int numberofwords = (strlen(DATA_32)/4) + ((strlen(DATA_32) % 4) != 0);
下面这个9是我直接赋值的,我就是打算写9个32位的数据,你需要些几个你就改成几;
int numberofwords = 9;
printf("number of words = %d",numberofwords);
//flash写入之前需要解锁flash
HAL_FLASH_Unlock();
//擦除flash,准备写入数据
// uint32_t StartPage = GetPage(StartPageAddress);
uint32_t EndPageAdress = StartPageAddress + numberofwords*4;
// uint32_t EndPage = GetPage(EndPageAdress);
//擦除页面的动作,擦除页面的地址,擦除页面的数量
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.PageAddress = StartPageAddress;
EraseInitStruct.NbPages =1;
//下面这个函数就是擦除页面的函数
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK)
{
//擦除页面时发生的错误,送到这里处理
return HAL_FLASH_GetError ();
}
//一个字一个字的写入flash
StartPageAddress=0x08007000;
while (sofar<numberofwords)
{
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, StartPageAddress, DATA_32[sofar]) == HAL_OK)
{
StartPageAddress += 4; // use StartPageAddress += 2 for half word and 8 for double word
sofar++;
}
else
{
/* Error occurred while writing data in Flash memory*/
return HAL_FLASH_GetError ();
}
}
StartPageAddress=0x08007000;
//给Flash上锁
HAL_FLASH_Lock();
return 0;
}
void Flash_Read_Data (uint32_t StartPageAddress, __IO uint32_t *DATA_32)
{
StartPageAddress=0x08007000;
while (1)
{
*DATA_32 = *(__IO uint32_t *)StartPageAddress;
if (*DATA_32 == 0xffffffff)
{
*DATA_32 = '\0';
break;
}
StartPageAddress += 4;
DATA_32++;
}
}
头文件:
#ifndef __flash_read_write_H__
#define __flash_read_write_H__
#include "stm32f1xx_hal.h"
/*FLASH写入程序*/
uint32_t Flash_Write_Data (uint32_t StartPageAddress, uint32_t * DATA_32);
/*FLASH读取打印程序*/
void Flash_Read_Data (uint32_t StartPageAddress, __IO uint32_t * DATA_32);
#endif
主函数应用文件代码示例:
下面这些是数据声明:
//从flash里面读出的数据存在该数组
uint32_t start_addr=0x08007000;
__IO uint32_t data_read_fromflash[9];
uint32_t data_tobe_wrote[9] = {78,21,89,91,12,23,6789,321,9};
应用程序:
Flash_Write_Data(start_addr,data_tobe_wrote);
HAL_Delay(100);
Flash_Read_Data(start_addr,data_read_fromflash);
int i=0;
for(i=0;i<9;i++){
printf("\r\nRx_Data: %d\r\n",data_read_fromflash[i]);
HAL_Delay(100);
}