Appearance
用 SPI NOR 双槽保存参数并回退到上次提交
W25Q128 的两个 4 KiB 扇区分别保留一份设置。换槽时先擦除备用扇区,读回主体后最后写提交字。掉电重启从有效记录中选比较新的代数。
板型与接线
选择专用 3.3 V W25Q128JV 模块,PA4/PA5/PA6/PA7 接 CS/SCK/MISO/MOSI。PA0 触发保存,PB2 观察闪灯。实验预留 0xFFE000 与 0xFFF000 两个扇区,接入前确认其内容可覆盖。
沿执行路径读代码
- SPI 方向固定为 Mode 0。读 JEDEC ID,核对 EF 40 18,再加载两个记录。
- 每次更新都重新读槽,擦除较旧的一侧。页编程前确认写使能,擦除、编程后都等待器件退出 busy。
- 先比对主体,最后写提交字。下一次启动核对范围、CRC 和提交标记,再以无符号差选择较新记录。
完整源码
c
#include "stm32f4xx_hal.h"
#include "../../../c/debounce/debounce.h"
#include "store.h"
static SPI_HandleTypeDef spi;
static volatile uint32_t active_period, active_slot, generation, failed_saves, init_error;
void SysTick_Handler(void) { HAL_IncTick(); }
static bool transfer(const uint8_t *command, size_t command_size, const uint8_t *output,
uint8_t *input, size_t data_size)
{
// 1. 每个 SPI 命令有独立片选。命令、地址及可能的载荷在同一个事务内。
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
HAL_StatusTypeDef status = HAL_SPI_Transmit(&spi, command, (uint16_t)command_size, 20U);
if (status == HAL_OK && output != NULL)
{
status = HAL_SPI_Transmit(&spi, output, (uint16_t)data_size, 20U);
}
if (status == HAL_OK && input != NULL)
{
uint8_t dummy[NOR_RECORD] = {0};
status = HAL_SPI_TransmitReceive(&spi, dummy, input, (uint16_t)data_size, 20U);
}
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
return status == HAL_OK;
}
static bool read_status(uint8_t *value)
{
const uint8_t command = 0x05U;
return transfer(&command, 1U, NULL, value, 1U);
}
static bool wait_ready(uint32_t limit_ms)
{
const uint32_t start = HAL_GetTick();
do
{
uint8_t flags;
if (!read_status(&flags)) { return false; }
if ((flags & 1U) == 0U) { return true; }
HAL_Delay(1U);
} while ((uint32_t)(HAL_GetTick() - start) < limit_ms);
return false;
}
static bool write_enable(void)
{
uint8_t status;
const uint8_t command = 0x06U;
return wait_ready(1000U) && transfer(&command, 1U, NULL, NULL, 0U) &&
read_status(&status) && (status & 2U) != 0U;
}
// 参数区固定在最后两个扇区。所有写入仍由各命令的页/扇区边界约束。
static bool permitted(uint32_t address, size_t size)
{
return address >= NOR_SLOT_A && address < 0x1000000U && size <= 0x1000000U - address;
}
static bool nor_read_hw(void *context, uint32_t address, uint8_t *data, size_t size)
{
(void)context;
if (!permitted(address, size) || size > NOR_RECORD || !wait_ready(1000U)) { return false; }
const uint8_t command[] = {0x03U, (uint8_t)(address >> 16), (uint8_t)(address >> 8), (uint8_t)address};
return transfer(command, sizeof(command), NULL, data, size);
}
static bool nor_program_hw(void *context, uint32_t address, const uint8_t *data, size_t size)
{
(void)context;
const uint8_t command[] = {0x02U, (uint8_t)(address >> 16), (uint8_t)(address >> 8), (uint8_t)address};
return size > 0U && permitted(address, size) && size <= 256U - (address & 255U) &&
write_enable() && transfer(command, sizeof(command), data, NULL, size) && wait_ready(20U);
}
static bool nor_erase_hw(void *context, uint32_t address)
{
(void)context;
const uint8_t command[] = {0x20U, (uint8_t)(address >> 16), (uint8_t)(address >> 8), (uint8_t)address};
return (address == NOR_SLOT_A || address == NOR_SLOT_B) &&
write_enable() && transfer(command, sizeof(command), NULL, NULL, 0U) && wait_ready(1000U);
}
static bool init_board(void)
{
// 1. SPI1 Mode 0,PA4 默认释放片选。PA0/PB2 为输入和观察信号。
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_SPI1_CLK_ENABLE();
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
GPIO_InitTypeDef pins = {.Pin = GPIO_PIN_4, .Mode = GPIO_MODE_OUTPUT_PP};
HAL_GPIO_Init(GPIOA, &pins);
pins = (GPIO_InitTypeDef){.Pin = GPIO_PIN_0, .Mode = GPIO_MODE_INPUT};
HAL_GPIO_Init(GPIOA, &pins);
pins = (GPIO_InitTypeDef){.Pin = GPIO_PIN_2, .Mode = GPIO_MODE_OUTPUT_PP};
HAL_GPIO_Init(GPIOB, &pins);
pins = (GPIO_InitTypeDef){
.Pin = GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7, .Mode = GPIO_MODE_AF_PP,
.Speed = GPIO_SPEED_FREQ_HIGH, .Alternate = GPIO_AF5_SPI1,
};
HAL_GPIO_Init(GPIOA, &pins);
spi.Instance = SPI1;
spi.Init = (SPI_InitTypeDef){
.Mode = SPI_MODE_MASTER, .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_8BIT,
.CLKPolarity = SPI_POLARITY_LOW, .CLKPhase = SPI_PHASE_1EDGE, .NSS = SPI_NSS_SOFT,
.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16, .FirstBit = SPI_FIRSTBIT_MSB,
};
// 2. 等前一次可能尚未结束的写入,再核对 W25Q128 的 JEDEC ID。
const uint8_t command = 0x9FU;
uint8_t id[3];
return HAL_SPI_Init(&spi) == HAL_OK && wait_ready(1000U) &&
transfer(&command, 1U, NULL, id, sizeof(id)) &&
id[0] == 0xEFU && id[1] == 0x40U && id[2] == 0x18U;
}
int main(void)
{
// 1. 读取 A/B 槽。初值和最新提交由同一套规则恢复,SPI 失败则停机。
HAL_Init();
const NorIo io = {.read = nor_read_hw, .program = nor_program_hw, .erase_sector = nor_erase_hw};
NorSetting setting;
init_error = 1U;
if (!init_board()) { for (;;) {} }
init_error = 2U;
if (!nor_load(&io, &setting)) { for (;;) {} }
init_error = 0U;
Debounce key = {0};
uint32_t last = HAL_GetTick();
for (;;)
{
// 2. 按键稳定后提交新的值。失败继续用之前的参数,下一次另行尝试。
const uint32_t now = HAL_GetTick();
const bool pressed = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_SET;
if (debounce_update(&key, pressed, now, 20U) == KEY_PRESSED)
{
const uint32_t period = setting.period_ms > 900U ? 100U : setting.period_ms + 100U;
if (!nor_save(&io, period, &setting))
{
++failed_saves;
}
}
// 3. 让读回的参数控制板载 LED。调试变量同时显示生效的槽与代数。
active_period = setting.period_ms;
active_slot = setting.address;
generation = setting.generation;
if ((uint32_t)(now - last) >= setting.period_ms)
{
last = now;
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_2);
}
__WFI();
}
}下载双槽算法 · 下载主机检查 · 下载 CRC-32 · 下载按键消抖
c
#ifndef SKY_NOR_STORE_H
#define SKY_NOR_STORE_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "../../../c/common/crc32.h"
enum { NOR_SECTOR = 4096, NOR_BODY = 12, NOR_RECORD = 16 };
#define NOR_SLOT_A 0xFFE000U
#define NOR_SLOT_B 0xFFF000U
#define NOR_COMMIT 0x4B425341U
typedef struct
{
void *context;
bool (*read)(void *context, uint32_t address, uint8_t *data, size_t count);
bool (*program)(void *context, uint32_t address, const uint8_t *data, size_t count);
bool (*erase_sector)(void *context, uint32_t address);
} NorIo;
typedef struct
{
uint32_t generation, period_ms, address;
bool present;
} NorSetting;
static inline uint32_t nor_get_u32(const uint8_t *p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static inline void nor_put_u32(uint8_t *p, uint32_t v)
{
for (unsigned i = 0; i < 4U; ++i)
{
p[i] = (uint8_t)(v >> (8U * i));
}
}
static inline void encode_setting(uint8_t record[NOR_RECORD], uint32_t generation, uint32_t period)
{
nor_put_u32(record, generation);
nor_put_u32(record + 4U, period);
nor_put_u32(record + 8U, kb_crc32(record, 8U));
nor_put_u32(record + 12U, NOR_COMMIT);
}
static inline bool read_slot(const NorIo *io, uint32_t address, NorSetting *setting)
{
uint8_t bytes[NOR_RECORD];
if (!io->read(io->context, address, bytes, sizeof(bytes)))
{
return false;
}
setting->generation = nor_get_u32(bytes);
setting->period_ms = nor_get_u32(bytes + 4U);
setting->address = address;
setting->present = nor_get_u32(bytes + 12U) == NOR_COMMIT &&
setting->period_ms >= 100U && setting->period_ms <= 1000U &&
nor_get_u32(bytes + 8U) == kb_crc32(bytes, 8U);
return true;
}
// 任一槽读失败时保持输出不变,避免把未读到的较新记录误判为可擦除。
static inline bool nor_load(const NorIo *io, NorSetting *result)
{
// 1. A、B 都读取后,才在有效记录中选较新的代数。
NorSetting a, b;
if (!read_slot(io, NOR_SLOT_A, &a) || !read_slot(io, NOR_SLOT_B, &b))
{
return false;
}
const uint32_t difference = b.generation - a.generation;
if (b.present && (!a.present || (difference != 0U && difference < 0x80000000U)))
{
*result = b;
}
else
{
*result = a.present ? a : (NorSetting){.period_ms = 1000U};
}
return true;
}
// 保存成功后更新 result。失败时保留调用方已有值,下次可重新加载介质。
static inline bool nor_save(const NorIo *io, uint32_t period, NorSetting *result)
{
NorSetting latest;
if (period < 100U || period > 1000U || !nor_load(io, &latest))
{
return false;
}
// 1. 正在使用的槽保持原样,目标是另一扇区。无记录时从 A 开始。
const uint32_t address = latest.address == NOR_SLOT_A ? NOR_SLOT_B : NOR_SLOT_A;
uint8_t wanted[NOR_RECORD], readback[NOR_RECORD];
encode_setting(wanted, latest.generation + 1U, period);
if (!io->erase_sector(io->context, address) ||
!io->read(io->context, address, readback, sizeof(readback)))
{
return false;
}
for (size_t i = 0; i < sizeof(readback); ++i)
{
if (readback[i] != 0xFFU) { return false; }
}
// 2. 先写主体并比对,确认内容正确后才单独写提交字。
if (!io->program(io->context, address, wanted, NOR_BODY) ||
!io->read(io->context, address, readback, NOR_BODY) ||
memcmp(wanted, readback, NOR_BODY) != 0 ||
!io->program(io->context, address + NOR_BODY, wanted + NOR_BODY, NOR_RECORD - NOR_BODY))
{
return false;
}
// 3. 读回完整记录并确认激活候选,新的参数此时才交给调用者。
NorSetting committed;
if (!read_slot(io, address, &committed) || !committed.present ||
committed.generation != latest.generation + 1U || committed.period_ms != period)
{
return false;
}
*result = committed;
return true;
}
#endif编译和观察
准备 GNU Arm、CMake、Ninja 和 STM32CubeF4 V1.28.3。将固件包目录换成本机路径后,在仓库根目录运行以下命令。
sh
cmake -S examples/stm32/spi/nor-settings -B .work/sky-spi-nor-settings -G Ninja -DCUBE_F4_ROOT="D:/SDK/STM32Cube_FW_F4_V1.28.3"
cmake --build .work/sky-spi-nor-settings第一次按键以 100 ms 间隔翻灯。再按变 200 ms,active_slot 在两个地址间交替。按核心板复位键时保持外接模块供电,核对恢复的间隔和 generation。
练习
预测题 备用槽只写完主体,电源就断了,启动会用哪个参数?
核对预测
提交字尚未生效,启动继续选择原有效槽。
改动题 用主机检查程序把切断位置改到提交字的第二个字节前。
核对改法
保留旧参数。只有写全提交字且主体 CRC 正确,才会选新记录。
验证记录
主机内存模型逐字节切断 16 个写入位置,覆盖坏 CRC、读失败禁止擦除和代数回绕。固件已编译链接,实际芯片时序及中途掉电待实测。 Winbond W25Q128JV 产品与数据手册
运行独立主机检查。
powershell
New-Item -ItemType Directory -Force .work | Out-Null
gcc -std=c11 -Wall -Wextra -Werror -pedantic examples/stm32/spi/nor-settings/check.c -o .work/spi-nor-check.exe
& ./.work/spi-nor-check.exe