eeprom容量分成2份,一份作为常用区,一份作为备份区。
参数保存函数,先写入常用区,再写入备份区。
参数读取函数,先读常用区,成功则退出,不成功则读取备份区,成功则刷新常用区。
系统有多个参数,各个参数分开保存。这种方式的好处是方便扩展,新增参数不会影响到旧参数,缺点是开机加载参数时读取参数的次数多。
#define AT24C256
#ifdef AT24C256
#define EE_MODEL_NAME "AT24C256"
#define EE_DEV_ADDR 0xA0 /* 设备地址 */
#define EE_PAGE_SIZE 64 /* 页面大小(字节) */
#define EE_SIZE (32*1024) /* 总容量(字节) */
#define EE_ADDR_BYTES 2 /* 地址字节个数 */
#define EEP_ADDR_BACKUP_BASE (16*1024) /* 备份区起始地址 */
#endif
#define EEPROM_OP_TIME 3
int EEP_Save_Data( uint16_t addr, uint8_t* pdata, uint32_t len )
{
uint16_t l_u16WrCRC = 0;
uint16_t l_u16DataAddr = addr;
uint8_t l_u8aWrBuff[1024];
uint8_t ret,ret1;
uint8_t errcnt;
if(l_u16DataAddr > EE_SIZE) return -1;
memset(l_u8aWrBuff,0x00,sizeof(l_u8aWrBuff));
memcpy(l_u8aWrBuff,pdata,len);
l_u16WrCRC = GetCRC16(l_u8aWrBuff,len);
l_u8aWrBuff[ len ] = l_u16WrCRC & 0xff;
l_u8aWrBuff[ len + 1 ] = l_u16WrCRC >> 8;
errcnt = 0;
do
{
ret = WriteMultiByteToEEPROM( l_u8aWrBuff, l_u16DataAddr, len+2 );
}
while ( ret && ( ++errcnt < EEPROM_OP_TIME ) );
errcnt = 0;
do
{
ret1 = WriteMultiByteToEEPROM( l_u8aWrBuff, l_u16DataAddr + EEP_ADDR_BACKUP_BASE, len+2 );
}
while ( ret1 && ( ++errcnt < EEPROM_OP_TIME ) );
if( ret != 0 && ret1 != 0 )
{
return -2;
}
else
{
return 0;
}
}
int EEP_Read_Data( uint16_t addr, uint8_t* pdata, uint32_t len )
{
uint16_t l_u16Result = SUCCESS;
uint16_t calCRC = 0;
uint16_t l_u16RdCRC = 0;
uint16_t l_u16DataAddr = addr;
uint8_t l_u8aRdBuff[1024];
uint8_t ret,ret1;
uint8_t errcnt;
uint8_t flag;
if(l_u16DataAddr > EE_SIZE) return -1;
memset(l_u8aRdBuff,0x00,sizeof(l_u8aRdBuff));
errcnt = 0;
do
{
ret = ReadMultiByteFromEEPROM( l_u8aRdBuff, l_u16DataAddr, len+2 );
}
while ( ret && ( ++errcnt < EEPROM_OP_TIME ) );
if( ret == 0 )
{
memcpy(pdata,l_u8aRdBuff,len);
return 0;
}
else
{
errcnt = 0;
do
{
ret1 = ReadMultiByteFromEEPROM( l_u8aRdBuff, l_u16DataAddr + EEP_ADDR_BACKUP_BASE, len+2 );
}
while ( ret1 && ( ++errcnt < EEPROM_OP_TIME ) );
if(ret1 == 0)
{
memcpy(pdata,l_u8aRdBuff,len);
errcnt = 0;
do
{
ret = WriteMultiByteToEEPROM( l_u8aRdBuff, l_u16DataAddr, len+2 );
}
while ( ret && ( ++errcnt < EEPROM_OP_TIME ) );
return 0;
}
else
return -1;
}
}