STM32使用Flash存儲器當(dāng)作EEPROM來保持?jǐn)?shù)據(jù)
掃描二維碼
隨時(shí)隨地手機(jī)看文章
嵌入式應(yīng)用中經(jīng)常會遇到需要保存一些數(shù)據(jù)比如選項(xiàng)和設(shè)置等等,為了在設(shè)備關(guān)機(jī)或掉電情況下數(shù)據(jù)不丟失,我們會講數(shù)據(jù)保存在EEPROM里面。STM32系列MCU已經(jīng)被廣泛的使用,可是該芯片內(nèi)沒有EEPROM。如果外接一片EEPRM會增加硬件成本。
本文將以STM32F0為例介紹一種使用片內(nèi)Flash替代EEPROM的方法,僅供大家參考。
STM32F0芯片內(nèi)部Flash頁尺寸為1k。
首先程序需要使用STMicroelectronics提供的標(biāo)準(zhǔn)外設(shè)庫中的stm32f0xx_flash.h。如下:
#include "stm32f0xx_flash.h"
//定義常量 (以STM32F051R8為例)
#define FLASH_PAGE_SIZE((uint32_t)0x00000400)
#define FLASH_USER_START_ADDR((uint32_t)0x0800FC00)
#define FLASH_USER_END_ADDR((uint32_t)0x08010000)
//定義需保存數(shù)據(jù)的結(jié)構(gòu)
typedef struct
{
uint8_t sensitivity;
uint8_t track_no;
uint8_t high_lumi;
uint8_t low_lumi;
uint32_t hold_time;
uint8_t adc_output;
uint8_t dim_step;
uint16_t reserved;
uint32_t data_valid;
} _settings;
//為了方便變量的使用和在Flash里面的存貯,定義一聯(lián)合
typedef union
{
uint32_t DataAll[4];//因?yàn)樽兞拷Y(jié)構(gòu)總共為16 bytes,所以為4個(gè)32位變量
_settings DataI;
} settings;
//申明變量,注意一定要四字節(jié)對齊
A_ALIGNED volatile settings sensor_set;
//各功能函數(shù)
void UserErase(void)
{
FLASH_ErasePage(FLASH_USER_START_ADDR);
}
void UserRead(void)
{
int i;
uint32_t address_t;
address_t = FLASH_USER_START_ADDR;
for(i=0;i
{
sensor_set.DataAll[i] = *(__IO uint32_t *)address_t;
address_t += 4;
}
}
void UserWrite(void)
{
int i;
uint32_t address_t;
//Unlock the Flash to enable the flash control register access
FLASH_Unlock();
// Erase the FLASH pages
UserErase();//FLASH_ErasePage(FLASH_USER_START_ADDR);
// Program the user Flash area word by word
address_t = FLASH_USER_START_ADDR;
for(i=0;i
{
FLASH_ProgramWord(address_t, sensor_set.DataAll[i]);
address_t += 4;
}
// Lock the Flash to disable the flash control register access (recommended
//to protect the FLASH memory against possible unwanted operation)
FLASH_Lock();
}
//變量的使用
//在main()函數(shù)做初始化時(shí)讀取設(shè)置參數(shù)
UserRead();
//使用設(shè)置參數(shù)
if(sensor_set.DataI.sensitivity == 1)
{
//
}
//根據(jù)需要改變設(shè)置參數(shù)為3
sensor_set.DataI.sensitivity = 3;
UserWrite();//記住任何一個(gè)設(shè)置改變了都需要保存到Flash里面。