Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

 想实现断电保存少量的一些数据,stm32内部flash 排除运行程序占用空间后,还有剩余空间,可以把这些空间利用起来。

在操作前,推荐先看一下flash 存储 页、扇区、块概念和flash 每页地址,推荐: https://blog.csdn.net/ybhuangfugui/article/details/121463317

如果只是单纯想存、取数据,那就只关注页、每页大小、每页开始地址就可以了。

stm32f103c6t6 共 32 页每页 1kb(1024字节),也就是说,有32kb的断电保存空间,减去运行程序占用空间,剩下的,都是可操作空间。

涉及到基本感念:

8bit = 1b(byte 字节), 1024kb = 1Mb

uint8_t类型 占用 8bit(1b)

uint16_t类型 占用 16bit(2b)

uint32_t类型 占用 32bit(4b) 

uint64_t类型 占用 64bit(8b)

第一页开始地址: 0x8000000   结束地址: 0x80003FF

此处可以打开计算器试着计算一下: Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

 

 

获取运行程序实际大小:

在keil5中,执行rebuild, 完成后在结果中找到:

Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

 

 

把这几个值加起来,除1024(值的单位是b(byte)): 4244 + 292 + 16 + 1128 = 5680 ;  5680 / 1024 = 5.54kb,相当于程序占用了5页半,就当六页算。

在操作flash存储数据时,为防止影响到程序代码,可以隔一页,写数据。从第七页开始存储,(不一定必须隔一页,只是个人习惯)

0x8000000 + (1024 * 6) = 0x8001800

Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

此处乘 6不是 乘7,是因为页是从0开始的,0页地址是0x8000000,1页就是 0x8000000 + (1024) ,2页就是 0x8000000 + (1024 * 2).....

比如存储一个uint16_t类型数据,因为uint16_t占2字节,所以,0x8001800 + 2 = 0x8001802,这个变量内容就存储在:0x8001801和0x8001802两个地址中。

Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

 以下是我写的测试代码方法,测试存取数据操作:

#define PAGE_START_ADDRESS 0x8000000

//paramSizeKb 程序大小 //data 准备写入数据 //len 大小 bool flashWriteData(int paramSizeKb, uint64_t data[], size_t len) { HAL_FLASH_Unlock();//解锁flash //准备擦除整页,写入前需要擦除 FLASH_EraseInitTypeDef f; f.TypeErase = FLASH_TYPEERASE_PAGES;//页擦除 f.PageAddress = PAGE_START_ADDRESS + (1024 * paramSizeKb);//擦除页地址 f.NbPages = 1;//擦除1页 uint32_t PageError = 0; HAL_FLASHEx_Erase(&f, &PageError);//擦除PageError == 0xFFFFFFFF表示成功 if(PageError != 0xFFFFFFFF) { return false; } //开始写数据 uint32_t startAddressIndex = PAGE_START_ADDRESS + (1024 * paramSizeKb); //startAddressIndex += 8,写入位置,每次+8是因为存储的类型是uint64_t,占用64bit,8字节 for(int i = 0 ; i < len;i ++ , startAddressIndex += 8) { //写入数据 HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, startAddressIndex, data[i]); } //重新上锁 HAL_FLASH_Lock(); return true; } //读取数据 //paramSizeKb 程序大小 //data 读入数据 //len 读入数据长度 void flashReadData(int paramSizeKb, uint8_t *data, size_t len) { uint32_t startAddressIndex = PAGE_START_ADDRESS + (1024 * paramSizeKb); for(int i = 0; i < len; i++, startAddressIndex += 8){ data[i] = *(__IO uint32_t*)(startAddressIndex); } }

在烧写程序测试前,可以先用keil5 仿真功能测试一下,在测试时需要注意打开指定地址的读写访问操作:

打开运行指定地址读写访问:

首先开启debug调试: Debug -> Start/Stop Debug Session

进入debug调试后,进入Debug -> Memory Map... : Map Range处输入允许读写 开始地址,结束地址,逗号分割; 勾选Read Write复选框,点击Map Range 按钮添加允许读写操作区域。

Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据

 

 然后,就可以点击Keil5 HAL库操作 flash 存储数据(stm32f103c6t6),实现断电保存数据(Run F5)继续调试程序了。

 

完整测试文件内容main.c:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"
#include "stdbool.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */
//#define PAGE_START_ADDRESS 0x8000000
#define PAGE_START_ADDRESS 0x8008800

//paramSizeKb 程序大小
//data 准备写入数据
//len 大小
bool flashWriteData(int paramSizeKb, uint64_t data[], size_t len) {
    HAL_FLASH_Unlock();//解锁flash
    //准备擦除整页,写入前需要擦除
    FLASH_EraseInitTypeDef f;
    f.TypeErase = FLASH_TYPEERASE_PAGES;//页擦除
    f.PageAddress = PAGE_START_ADDRESS + (1024 * paramSizeKb);//擦除页地址
    f.NbPages = 1;//擦除1页
    
    uint32_t PageError = 0;
    HAL_FLASHEx_Erase(&f, &PageError);//擦除PageError == 0xFFFFFFFF表示成功
    if(PageError != 0xFFFFFFFF) {
        return false;
    }
    //开始写数据
    uint32_t startAddressIndex = PAGE_START_ADDRESS + (1024 * paramSizeKb);
    //startAddressIndex += 8,写入位置,每次+8是因为存储的类型是uint64_t,占用64bit,8字节
    for(int i = 0 ; i < len;i ++ , startAddressIndex += 8) {
        //写入数据
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, startAddressIndex, data[i]);
    }
    //重新上锁
    HAL_FLASH_Lock();
    return true;
}
//读取数据
//paramSizeKb 程序大小
//data 读入数据
//len 读入数据长度
void flashReadData(int paramSizeKb, uint64_t *data, size_t len) {
    uint32_t startAddressIndex = PAGE_START_ADDRESS + (1024 * paramSizeKb);
    for(int i = 0; i < len; i++, startAddressIndex += 8){
        data[i] = *(__IO uint32_t*)(startAddressIndex);
    }
}

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
    
  /* USER CODE END 1 */
  

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
    //程序大小 6k, rebuild 后 看Program Size: Code=4124 RO-data=292 RW-data=16 ZI-data=1128 ,把这几个数字(byte)加起来 / 1024
    //每页1k
    
  while (1)
  {
        //HAL_UART_Transmit(&huart1, (uint8_t[]){0x00, 0x00, 0x00}, 3, 1000);
    /* USER CODE END WHILE */
        uint8_t data[3];
        if (HAL_UART_Receive(&huart1, data, 3, 100) == HAL_OK) {
            //0xAA or 0xBB
            uint8_t cmd = 0xFF;
            for(int i = 0; i < 3; i++) {
                if(data[i] != data[0]) {
                    HAL_UART_Transmit(&huart1, data, 3, 1000);
                    break;
                }
                if (i + 1 == 3) {
                    cmd = data[0];
                }
            }
            if(cmd == 0xAA) {
                uint64_t writeData[5] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE};
                if(flashWriteData(6, writeData, 5)) {
                    HAL_UART_Transmit(&huart1, (uint8_t[]){0xAA, 0xAA, 0xAA}, 3, 1000);
                }else{
                    HAL_UART_Transmit(&huart1, (uint8_t[]){0xFF, 0xFF, 0xFF}, 3, 1000);
                }
                
            }
            if(cmd == 0xBB) {
                uint64_t readData[5];
                flashReadData(6, readData, 5);
                //HAL_UART_Transmit(&huart1, (uint8_t[]){0xBB, 0xBB, 0xBB}, 3, 1000);    
                HAL_UART_Transmit(&huart1, (uint8_t[]){0xFF, 0xFF, 0xFF}, 5, 1000);    
                
            }
            if(cmd != 0xAA && cmd != 0xBB) {
                HAL_UART_Transmit(&huart1, (uint8_t[]){0xFF, 0xFF, 0xFF}, 3, 1000);    
            }
        }
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

此处代码通过串口发送0xAA 0xAA 0xAA,设置0xAA, 0xBB, 0xCC, 0xDD, 0xEE;发送0xBB 0xBB 0xBB 读取存入的内容。

 

刚开始接触STM32相关硬件,如果有误导的地方,恳请一定指出! 防止误让其他人走弯路。

上一篇:手把手系列--华邦W25Q64JV Flash操作指南


下一篇:资产监测设备中HCL190FLAS擦写问题分析——HCL190