// 单独的计算校验和函数
unsigned char calculateChecksum(const PARAM_SAVE_T *param)
{
unsigned char checksum = 0;
const unsigned char *pData = (const unsigned char *)param;
for (int i = 0; i < sizeof(PARAM_SAVE_T) - 1; i++) // 减1,排除checksum字段本身
{
checksum += pData[i];
}
return checksum;
}
// 读取并校验数据完整性的函数
char readAndCheckParam(const PARAM_SAVE_T *param)
{
unsigned char calculatedChecksum = calculateChecksum(param);
if (calculatedChecksum == param->checksum)
{
return 1; // 数据有效
}
else
{
return 0; // 数据损坏
}
}
// 更新结构体中的checksum字段
void updateChecksum(PARAM_SAVE_T *param)
{
unsigned char checksum = calculateChecksum(param);
param->checksum = checksum;
}
/*
*********************************************************************************************************
* 函 数 名: LoadParam
* 功能说明: 从Flash读参数到g_saveParam
* 形 参:无
* 返 回 值: 无 PARAM_SAVE_T g_saveParam;
*********************************************************************************************************
*/
void LoadParam(void)
{
unsigned char CheckParam = FALSE;
/* 读取CPU Flash中的参数 */
if (MD_OK == bsp_ReadCpuFlash(PARAM_ADDR, (unsigned char *)&g_saveParam, sizeof(PARAM_SAVE_T)))
{
// 读取并校验数据
if (readAndCheckParam(&g_saveParam))
{
if (g_saveParam.ParamVer != PARAM_VER)
{
CheckParam = TRUE;
}
}
else
{
// 数据无效时的处理
CheckParam = TRUE;
}
// 将新参数写入Flash
if (CheckParam)
{
g_saveParam.ParamVer = PARAM_VER;
g_saveParam.voiceSwitch = TRUE;
g_saveParam.set_VOL = 90;
g_saveParam.ota_flag = TRUE;
g_saveParam.pot_type_flag = 0;
g_saveParam.server_type_flag = Guo_Type_RELE_SERVER;
// g_saveParam.server_type_flag = Guo_Type_TEST_SERVER;
SaveParam(); // 将新参数写入Flash
}
// 数据有效时的处理
memcpy((uint8_t *)&g_lastsaveParam, (uint8_t *)&g_saveParam, sizeof(PARAM_SAVE_T));
}
bsp_ReadCpuFlash(PARAM_ADDR, (unsigned char *)&g_saveParam, sizeof(PARAM_SAVE_T));
}
/*
*********************************************************************************************************
* 函 数 名: SaveParam
* 功能说明: 将全局变量g_tParam 写入到CPU内部Flash
* 形 参: 无 PARAM_SAVE_T g_saveParam;
* 返 回 值: 无
*********************************************************************************************************
*/
void SaveParam(void) // 这里需要时间间隔存数据
{
// 计算并更新checksum
updateChecksum(&g_saveParam);
/* 将全局的参数变量保存到 CPU Flash */
bsp_WriteCpuFlash(PARAM_ADDR, (unsigned char *)&g_saveParam, sizeof(PARAM_SAVE_T));
bsp_DelayMS(10);
}
void LoadParamPoll(void) //
{
if (0 != memcmp((uint8_t *)&g_lastsaveParam, (uint8_t *)&g_saveParam, sizeof(PARAM_SAVE_T)))
{
memcpy((uint8_t *)&g_lastsaveParam, (uint8_t *)&g_saveParam, sizeof(PARAM_SAVE_T));
SaveParam();
}
}
calcChecksum
最新推荐文章于 2024-08-22 17:27:46 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)