当前位置:   article > 正文

STM32内部Flash模拟EEPROM磨损均衡算法_flash均衡擦写算法

flash均衡擦写算法


前言

许多场合下我们需要掉电保存一些参数,使用EEPROM会增加成本且开发麻烦。利用内部FLASH模拟EEPROM可在节约硬件成本的情况下通过简单的算法很方便地实现同样的功能。


一、为什么需要使用磨损均衡算法

1、EEPROM按字节擦写数据,内部FLASH只能按页擦除,按半字写入;
2、FLASH 单个存储位只能从1变为0,而不能从0变成1;
3、擦除过程就是把所有的存储位都写1;
4、FLASH 擦写次数是有限,一般是 10W 次;
以上FLASH特效决定需要一种比较高效算法,总不能每次更改数值就擦除一次。
本损均衡算法支持存储多个参数,最大限度降低FLASH的擦除次数。

二、算法均衡说明

1、存储结构

1、每个存储单元占用4字节:键(1byte)+值(2byte)+校验和(1byte);
2、键(1byte)除了用来区分参数,也用来分辨存储单元是否为空,所以键值最大为254。

2、读写方案

1、开机遍历FLASH中所有记录,将已有参数读取到数组中备用(存在最后位置的记录为最新记录),若改参数缺失则使用默认参数,同时获得下个可用存储单元的位置;
2、每次更新参数使先修改数组中的参数值,再在FLASH中创建一条最新记录,同时更新下个可用存储单元的位置;
3、若当前页中存储单元用尽,先擦除页,再从起始位置开始新建所有参数的记录;
4、每次读取某个参数使只需到数组中查找即可。

三、算法实现代码

1.头文件

#ifndef __FLASH_H__
#define __FLASH_H__

/* Includes ------------------------------------------------------------------*/
#include "stdint.h"

/* public define ------------------------------------------------------------*/
#define D_PAGE_SIZE              (uint32_t)FLASH_PAGE_SIZE
#define D_PAGE_ADDR(PageNum)     (FLASH_BASE + (D_PAGE_SIZE * (PageNum)))
#define D_FLASH_START_ADDR        D_PAGE_ADDR(20)   //Flash起始地址
#define D_PARA_NUM                10     //参数个数必须小于255

/* public typedef -----------------------------------------------------------*/
/* public constants --------------------------------------------------------*/
/* public variables ---------------------------------------------------------*/
/* public functions prototypes ---------------------------------------------*/
void FlashInitPara(uint16_t aDefVal[D_PARA_NUM]);
uint8_t FlashReadPara(uint8_t Key,uint16_t *pVal);
void FlashWritePara(uint8_t Key,uint16_t Val);

#endif 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2.源文件


/* Includes ------------------------------------------------------------------*/
#include "flash.h"
#include "stm32f1xx_hal.h"
#include "debug.h"

extern void  FLASH_PageErase(uint32_t PageAddress);

/* Private define ------------------------------------------------------------*/
#define D_PARA_KAY_NULL   0XFF

/* Private typedef -----------------------------------------------------------*/

#pragma pack(1)
typedef struct
{
    uint8_t Key;
    uint16_t Val;
    uint8_t Sum;
} ST_DATA_PACK, *PST_DATA_PACK;
#pragma pack()

typedef struct
{
    uint8_t Exist;
    uint16_t Val;
} ST_PARA_INFO, *PST_PARA_INFO;

/* Private constants --------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
static ST_PARA_INFO s_aParaTbl[D_PARA_NUM] = {0};

static uint16_t s_NewWriteIdx = 0;

/* Private function prototypes -----------------------------------------------*/
static void FlashEaserPage(void);
static void CreateRecord(uint8_t Key);
static uint8_t CalcCheckSum(const uint8_t *pData, uint32_t Len);

/* public constants --------------------------------------------------------*/
/* public variables ---------------------------------------------------------*/
/* public function  -----------------------------------------------*/

/********************************************************************
* name         : FlashInitPara
* description  : 初始化保存参数
* Input        :
* Output       : none
* Return       : none
********************************************************************/
void FlashInitPara(uint16_t aDefVal[D_PARA_NUM])
{
    for(uint16_t i = 0; i < D_PAGE_SIZE / sizeof(ST_DATA_PACK); i++)
    {
        uint32_t ReadAddr = D_FLASH_START_ADDR + sizeof(ST_DATA_PACK) * i;
        PST_DATA_PACK pstPack = (PST_DATA_PACK)ReadAddr;

        if(pstPack->Key != D_PARA_KAY_NULL)
        {
            uint8_t Sum = CalcCheckSum((uint8_t *)pstPack,3);
            if(pstPack->Sum == Sum)
            {            
                if(pstPack->Key < D_PARA_NUM)
                {
                    s_aParaTbl[pstPack->Key].Exist = 1;
                    s_aParaTbl[pstPack->Key].Val = pstPack->Val;
                }
            }
        }
        else
        {
            s_NewWriteIdx = i;
            DebugPrintf("init s_NewWriteIdx = %d\n", s_NewWriteIdx);
            break;
        }
    }

    for(uint16_t i = 0; i < D_PARA_NUM; i++)
    {
        //flash找不到参数,使用默认值
        if(!s_aParaTbl[i].Exist)
        {
            s_aParaTbl[i].Exist = 1;
            s_aParaTbl[i].Val = aDefVal[i];
            CreateRecord(i);
        }
        else
        {
            DebugPrintf("init key:%d,Val:0x%x\n", i, s_aParaTbl[i].Val);
        }
    }
}

/********************************************************************
* name         : FlashEaserPage
* description  : Flash擦除页
* Input        :
* Output       : none
* Return       : none
********************************************************************/
static void FlashEaserPage(void)
{
    DebugPrintf("%s\n", __func__);

    /* -1- Unlock the Flash Bank Program Erase controller */
    HAL_FLASH_Unlock();

    /* -2- Clear All pending flags */
    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR);

    /* -3- erase the FLASH pages */
    FLASH_PageErase(D_FLASH_START_ADDR);
    FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
    CLEAR_BIT(FLASH->CR, FLASH_CR_PER);

    /* -4- Lock the Flash Bank Program Erase controller */
    HAL_FLASH_Lock();
}

/********************************************************************
* name         : CreateRecord
* description  : 备份最新参数
* Input        :
* Output       : none
* Return       : none
********************************************************************/
static void CreateRecord(uint8_t Key)
{
    ST_DATA_PACK stPack = {0};

    if(s_NewWriteIdx == D_PAGE_SIZE / sizeof(ST_DATA_PACK))
    {
        FlashEaserPage();
        s_NewWriteIdx  = 0;
        HAL_FLASH_Unlock();
        for(uint16_t j = 0; j < D_PARA_NUM; j++)
        {
            if(s_aParaTbl[j].Exist)
            {
                stPack.Key = j;
                stPack.Val = s_aParaTbl[j].Val;
                stPack.Sum = CalcCheckSum((uint8_t *)&stPack,3);
                uint32_t Addr = D_FLASH_START_ADDR + sizeof(ST_DATA_PACK) * j;
                HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Addr, *(uint32_t *)&stPack);
                s_NewWriteIdx += 1;
                DebugPrintf("s_NewWriteIdx = %d\n", s_NewWriteIdx);
            }
        }
        HAL_FLASH_Lock();
    }
    else
    {
        stPack.Key = Key;
        stPack.Val = s_aParaTbl[Key].Val;
        stPack.Sum = CalcCheckSum((uint8_t *)&stPack,3);
        uint32_t Addr = D_FLASH_START_ADDR + sizeof(ST_DATA_PACK) * s_NewWriteIdx;
        HAL_FLASH_Unlock();
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Addr, *(uint32_t *)&stPack);
        HAL_FLASH_Lock();
        s_NewWriteIdx += 1;
        DebugPrintf("s_NewWriteIdx = %d\n", s_NewWriteIdx);
    }
}

/********************************************************************
* name         : FlashReadPara
* description  : 读取指定参数
* Input        :
* Output       : none
* Return       : none
********************************************************************/
uint8_t FlashReadPara(uint8_t Key, uint16_t *pVal)
{
    if(Key < D_PARA_NUM)
    {
           if(s_aParaTbl[Key].Exist)
           {
               *pVal = s_aParaTbl[Key].Val;
               return 1;
           }
    }
    return 0;
}

/********************************************************************
* name         : FlashWritePara
* description  : 写入指定参数
* Input        :
* Output       : none
* Return       : none
********************************************************************/
void FlashWritePara(uint8_t Key, uint16_t Val)
{
    if(Key < D_PARA_NUM)
    {
        s_aParaTbl[Key].Val = Val;
        s_aParaTbl[Key].Exist = 1;
        CreateRecord(Key);
    }
}

/********************************************************************
* name         : CalcCheckSum
* description  : 计算校验和
* Input        :
* Output       : none
* Return       : none
********************************************************************/
static uint8_t CalcCheckSum(const uint8_t *pData, uint32_t Len)
{
    uint32_t Sum = 0;
    const uint8_t *pDataEnd = pData + Len;

    while(pData < pDataEnd)
    {
        Sum += *pData++;
    }

    return (Sum & 0xFF);
}

/********************************************************************
* name         : FlashTest
* description  : 测试代码
* Input        :
* Output       : none
* Return       : none
********************************************************************/
void FlashTest(void)
{
    uint16_t aDefPara[D_PARA_NUM] = {0x0000, 0x1111, 0x2222, 0x3333, 0x4444,
                                     0x5555, 0x6666, 0x7777, 0x8888, 0x9999};

    //FlashEaserPage();
    FlashInitPara(aDefPara);

    for(uint16_t i = 0; i < 100; i++)
    {
        uint16_t Key = i % D_PARA_NUM;

        if(Key % 2 == 0)
        {
            continue;
        }

        uint16_t Val = 0;
        if(FlashReadPara(Key, &Val) > 0)
        {
//            DebugPrintf("before i:%d,key:%d,Val:0x%x\n", i, Key, Val);

            // write data into flash
            FlashWritePara(Key, Val + 1);

            //read from flash and print
            if(FlashReadPara(Key, &Val) > 0)
            {
                DebugPrintf("after i:%d,key:%d,Val:0x%x\n", i, Key, Val);
            }
            else
            {
                DebugPrintf("i = %d,read fail\n", i);
            }
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266

总结

以上代码已在STM32F103上多次验证,但仍可能有bug,如有发现请评论留言,谢谢!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/429308
推荐阅读
相关标签
  

闽ICP备14008679号