Append records to a flash log with a sequence counter
Append fixed-size records to a flash log, giving each one a sequence counter so the newest is found after a power cut. Works on any NOR flash, C99.
NOR flash can only turn 1 bits into 0 bits until you erase a whole sector, so a log that appends records never needs to erase until it is full. Give each record a sequence counter and a check value, and the newest valid record can be found after a reset by scanning the sector. The trick that makes this safe against power loss is that an erased slot reads as all 0xFF, so a half-written record is detected by its failed check rather than trusted.
#include <stdint.h>
typedef struct {
uint32_t seq; // 0xFFFFFFFF means the slot is still erased
uint32_t value;
uint32_t check; // seq ^ value ^ 0xA5A5A5A5
} record_t;
#define SLOTS 8
extern const record_t log_area[SLOTS]; // sector mapped in flash
int find_latest(void) {
int best = -1;
uint32_t best_seq = 0;
for (int i = 0; i < SLOTS; i++) {
const record_t *r = &log_area[i];
if (r->seq == 0xFFFFFFFFu) break; // first erased slot ends the log
if (r->check != (r->seq ^ r->value ^ 0xA5A5A5A5u)) continue;
if (best < 0 || r->seq > best_seq) { best = i; best_seq = r->seq; }
}
return best;
}With slots holding sequence 1, 2 and 3 (the third written fully) and the fourth erased, the loop stops at index 3.
find_latest() returns 2The sequence counter, not the position, decides which record wins, so the same code survives a log that wraps after an erase. Keep one sector's worth of slots at most, since erasing is the only way to reclaim space and takes the longest. A wear-levelled filesystem is the better answer once records vary in size.