|
下面的程序是产品验证过的。
#include "flash.h"
/*
**-----------------------------------------------------------------------------
**
** Abstract:
** 读FLASH选项字节的值
**
** Parameters:
** Address 选项字节地址
**
** Returns:
** 返回选项字节某个地址的值,高8位为Address的值,低8位为Address+1的值
**
**-----------------------------------------------------------------------------
*/
unsigned int Flash_ReadOptionByte(unsigned int Address)
{
unsigned char value_optbyte, value_optbyte_complement = 0;
unsigned int res_value = 0;
value_optbyte = *((@near unsigned char*)Address);
value_optbyte_complement = *(((@near unsigned char*)Address)+1);
res_value = (unsigned int)value_optbyte << 8;
res_value |= (unsigned int)value_optbyte_complement;
return(res_value);
}
/*
**-----------------------------------------------------------------------------
**
** Abstract:
** 擦除选项字节某个地址的值
**
** Parameters:
** Address 选项字节某个地址
**
** Returns:
** None
**
**-----------------------------------------------------------------------------
*/
void Flash_EraseOptionByte(unsigned int Address)
{
FLASH_CR2 |= 0x80; //对选项字节进行写操作
FLASH_NCR2 &= ~0x80;
*((@near unsigned char*)Address) = 0x00;
*((@near unsigned char*)(Address+1)) = 0xff;
Flash_WaitForLastOperation();
FLASH_CR2 &= ~0x80; //对选项字节写禁止
FLASH_NCR2 |= 0x80;
}
/*
**-----------------------------------------------------------------------------
**
** Abstract:
** 写选项字节某个址址的值
**
** Parameters:
** Address 选项字节某个地址 Data 要写的数据
**
** Returns:
** None
**
**-----------------------------------------------------------------------------
*/
void Flash_ProgramOptionByte(unsigned int Address, unsigned char Data)
{
FLASH_CR2 |= 0x80; //对选项字节进行写操作
FLASH_NCR2 &= ~0x80;
FLASH_DUKR = 0xae; //解除写保护密钥
FLASH_DUKR = 0x56;
*((@near unsigned char*)Address) = Data;
*((@near unsigned char*)(Address+1)) = ~Data;
Flash_WaitForLastOperation();
FLASH_CR2 &= ~0x80; //对选项字节写禁止
FLASH_NCR2 |= 0x80;
}
/*
**-----------------------------------------------------------------------------
**
** Abstract:
** 选项字节擦写等待
**
** Parameters:
** None
**
** Returns:
** None
**
**-----------------------------------------------------------------------------
*/
unsigned char Flash_WaitForLastOperation(void)
{
unsigned char flagstatus = 0;
unsigned int timeout = 0x1000;
while((flagstatus == 0)&&(timeout != 0))
{
flagstatus = FLASH_IAPSR & 0x05;
timeout--;
}
if(timeout == 0)
{
flagstatus = 0x02; //time out error
}
}
/*
**-----------------------------------------------------------------------------
**
** Abstract:
** 对选项字节的操作
**
** Parameters:
** Address 选项字节某个地址 Data 要写的数据
**
** Returns:
** None
**
**-----------------------------------------------------------------------------
*/
void Flash_OptionOperation(unsigned int Address, unsigned char Data, unsigned int Value)
{
unsigned int temp = 0;
do
{
temp = Flash_ReadOptionByte(Address);
if(temp != Value)
Flash_ProgramOptionByte(Address, Data);
if(temp == Value)
temp = 0;
}while(temp);
FLASH_IAPSR &= ~0x08; //EEPROM写保护使能
} |
|