#include "para.h" #include "w25qxx.h" #include "crc.h" #include "string.h" // 默认参数 static const para_t default_para = { .ver = 1, .mode = 1, .light_mode_hours = 10, .time_mode_start = 0, .time_mode_end = 23, .photo_interval = 60, .crc = 0x0000 // 占位符,实际会重新计算 }; para_t para; int para_init(void) { para_t temp; W25qxx_Init(); if (para_read(&temp) == 0) { // 如果 CRC 校验通过,则使用读出的数据 memcpy(¶, &temp, sizeof(para_t)); return 0; } else { // 否则使用默认值 memcpy(¶, &default_para, sizeof(para_t)); return -1; } return 0; } int para_read(para_t *p) { // 从 Flash 读取整个结构体 W25qxx_ReadBytes((uint8_t *)p, PARA_FLASH_ADDR, sizeof(para_t)); // 验证 CRC uint16_t crc = CRC16((uint8_t *)p, sizeof(para_t) - sizeof(uint16_t)); if (crc != p->crc) { return -1; } return 0; } int para_write(para_t *p) { para_t temp; // 先尝试读取当前页是否为空 W25qxx_ReadBytes((uint8_t *)&temp, PARA_FLASH_ADDR, sizeof(para_t)); if (memcmp(&temp, p, sizeof(para_t)) == 0) { // 数据未改变,无需写入 return 0; } // 计算 CRC(排除自身字段) p->crc = CRC16((uint8_t *)p, sizeof(para_t) - sizeof(uint16_t)); // 写入 Flash W25qxx_EraseSector(PARA_FLASH_ADDR/w25qxx.SectorSize); W25qxx_WritePage((uint8_t *)p, PARA_FLASH_ADDR / w25qxx.PageSize, 0, sizeof(para_t)); // 验证写入是否成功 para_t verify; W25qxx_ReadPage((uint8_t *)&verify, PARA_FLASH_ADDR / w25qxx.PageSize, 0, sizeof(para_t)); if (memcmp(p, &verify, sizeof(para_t)) != 0) { return -1; } return 0; }