内部FLASH和EEPROM这种掉电后还能保存内容的内存统称为non-volatile memory(NVM),STM32L053内部有2K的EEPROM.4 q3 ~: m# P, [- H2 L$ s; O
内部EEPROM的页大小为一个Word为单位,擦除是必须以页为单位,所以库函数里的擦除函数也是每次擦除4个字节:
5 z3 @3 N4 E& p) k* J8 w1 H/ r2 V3 B4 U3 H+ ~& C( J4 X1 m
- <p>/** </p><p> * @brief Erase a word in data memory. </p><p> * @param Address: specifies the address to be erased. </p><p> * @note To correctly run this function, the HAL_FLASHEx_DATAEEPROM_Unlock() function </p><p> * must be called before. </p><p> * Call the HAL_FLASHEx_DATAEEPROM_Lock() to the data EEPROM access </p><p> * and Flash program erase control register access(recommended to protect </p><p> * the DATA_EEPROM against possible unwanted operation). </p><p> * @retval HAL status </p><p> */ </p><p>HAL_StatusTypeDef HAL_FLASHEx_DATAEEPROM_Erase(uint32_t Address) </p><p>{ </p><p> HAL_StatusTypeDef status = HAL_OK; </p><p> </p><p> /* Check the parameters */ </p><p> assert_param(IS_FLASH_DATA_ADDRESS(Address)); </p><p> </p><p> /* Wait for last operation to be completed */ </p><p> status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); </p><p> </p><p> if(status == HAL_OK) </p><p> { </p><p> /* Clean the error context */ </p><p> ProcFlash.ErrorCode = HAL_FLASH_ERROR_NONE; </p><p> </p><p> /* Write "00000000h" to valid address in the data memory" */ </p><p> *(__IO uint32_t *) Address = 0x00000000; </p><p> </p><p> status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE); </p><p> } </p><p> </p><p> return status; </p><p>} </p>
复制代码 ; \- r9 X9 @1 _ L1 T
写EEPROM的顺序和使用flash类似,要先解锁(UNLOCK) 才能写,写的时候可以字节、半字、字为单位都可以。
: n# ^) ?. ^9 I; B# ]9 j% _( i9 c0 H/ Y+ X: M6 m
写的时候可以不擦除,内部会自动擦除。需要注意的是写EEPROM会消耗固定的时间,所以需要在程序对时间要求严格时3 \: x0 }5 S* _6 X: t
2 U, g! o$ F2 E, K' m& d正确安排写EEPROM的时机。
$ R. X" T$ \; ]. W
: b' ]2 ]3 D! c写EEPROM的函数如下:( K# E! D$ Z3 R6 j
4 R0 c1 k! q# ?: g
- <p>void EEPROM_Write(uint16_t WriteAddr,uint8_t *pBuffer,uint16_t NumToWrite) </p><p>{ </p><p> uint16_t t; </p><p> HAL_FLASHEx_DATAEEPROM_Unlock(); </p><p> for(t = 0;t < NumToWrite;t++) </p><p> { </p><p> HAL_FLASHEx_DATAEEPROM_Program(FLASH_TYPEPROGRAMDATA_BYTE,DATA_EEPROM_BASE + WriteAddr + t,*(pBuffer + t)); </p><p> } </p><p> HAL_FLASHEx_DATAEEPROM_Lock(); </p><p>} </p>
复制代码 M9 l; ]$ u8 P
main函数里面先写EEPROM,然后再读出来验证是否和写一样,一样的话点亮LED:/ ?( P: R5 e* @* ^+ u6 s; Y
' N7 }- U& ~( f- x" N- <p>#include "main.h" </p><p>uint8_t Test[25] = "http://www.eepw.com.cn/"; </p><p>uint8_t Buff[25]; </p><p>int main(void) </p><p>{ </p><p> uint8_t res; </p><p> HAL_Init(); </p><p> SystemClock_Config(); </p><p> LED_Init(); </p><p> EEPROM_Write(0,Test,25); </p><p> EEPROM_Read(0,Buff,25); </p><p> res = strcmp((const char*)Buff,(const char*)Test); </p><p> if(0 == res) </p><p> { </p><p> while(1) </p><p> { </p><p> HAL_Delay(500); </p><p> LED_TOG; </p><p> } </p><p> } </p><p>} </p><p></p>
复制代码 , |& R* G3 p0 [2 j; F; S6 X0 i
9 e6 I8 F; {" W5 n
|