Flash, EEPROM and FRAM
Erase before write, endurance, wear levelling and surviving power loss.
Memory that survives power-off
Every product stores something that must outlive a power cycle: calibration constants, configuration, counters, logs, the firmware itself. The memory types that keep data without power behave very differently from RAM, and getting them wrong produces some of the most expensive field failures: corrupted settings after a brown-out, or flash worn out after two years.
The memory types
| Type | Erase unit | Write unit | Endurance (erase cycles) | Typical use |
|---|---|---|---|---|
| Internal MCU flash | Page or sector: 1 KB to 128 KB | 32 to 256 bits | 10,000 (some parts 100,000) | Firmware; small amounts of data |
| External NOR flash (SPI/QSPI) | 4 KB sector, 64 KB block | Page of 256 bytes | ~100,000 | Firmware images, logs, file systems |
| NAND flash | Block of 128 KB+ | Page of 2 KB+ | 3,000 to 100,000 (needs ECC, bad blocks) | Large storage; usually behind a controller (eMMC, SD) |
| EEPROM (I2C/SPI, or on-chip in some MCUs) | Byte or page | Byte or page | 1,000,000 | Small, frequently changed settings |
| FRAM / MRAM | None: write in place | Byte | 10^12 or more, effectively unlimited | High-rate logging, counters, fast and low power |
How flash differs from RAM
- Erase before write. Erased flash reads as all ones (
0xFF). Programming can only change bits from 1 to 0. To turn a 0 back into a 1, you must erase the whole page or sector. - Large erase units. Changing one byte in a 4 KB sector means: read the sector, erase it, write it all back. Power loss in between loses everything in that sector.
- Slow and blocking. A page erase takes milliseconds to tens of milliseconds; a sector erase on internal flash can take hundreds of milliseconds. On single-bank internal flash the CPU cannot fetch code from the same bank while it is programming, so it stalls unless the flash routine runs from RAM.
- Limited endurance. Each erase wears the cells; after the rated count, bits stop holding their value reliably.
- Data retention. Typically 10 to 20 years, shorter at high temperature and after many cycles.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* A model of a flash page: programming can only clear bits; only erase sets them back to 1. */
#define PAGE 8
static uint8_t page[PAGE];
static void erase(void) { memset(page, 0xFF, PAGE); }
static void program(int at, uint8_t value) { page[at] &= value; } /* 1 -> 0 only */
int main(void) {
erase();
program(0, 0x5A);
printf("after programming 0x5A: 0x%02X\n", page[0]);
program(0, 0xA5); /* try to overwrite without erasing */
printf("after programming 0xA5 on top: 0x%02X (not 0xA5!)\n", page[0]);
erase();
program(0, 0xA5);
printf("after erase, then 0xA5: 0x%02X\n", page[0]);
return 0;
}
Wear levelling
If a counter updated every minute is written to the same flash sector, a 10,000-cycle sector is worn out in a week. Wear levelling spreads writes over many locations so each one is erased rarely.
The simplest robust scheme for small records is an append-only log in two or more sectors:
- Each write appends a new copy of the record (with a sequence number and CRC) to the next free slot in the active sector.
- Reading scans for the last valid record.
- When the sector is full, copy the latest record to the next sector, then erase the old one.
A 4 KB sector holding 32-byte records takes 128 updates per erase, multiplying its lifetime by 128.
#include <stdio.h>
int main(void) {
double endurance = 10000; /* erase cycles per sector */
double writes_per_day = 24 * 60; /* a counter saved every minute */
int sectors = 2, sector_bytes = 4096, record_bytes = 32;
double naive_days = endurance / writes_per_day;
double records_per_erase = (double)sector_bytes / record_bytes;
double logged_days = endurance * records_per_erase * sectors / writes_per_day;
printf("rewriting one location: worn out after %.0f days\n", naive_days);
printf("append log over %d sectors: worn out after %.0f years\n", sectors, logged_days / 365);
return 0;
}
Vendors provide "EEPROM emulation" libraries that implement exactly this on internal flash. File systems designed for flash (LittleFS) and flash translation layers in SD cards and eMMC do the same at a larger scale.
Surviving power loss
Power can fail at any instruction, including in the middle of an erase or a write. Rules for data that must survive:
- Never erase the only valid copy. Write the new copy first, verify it, then invalidate or erase the old one.
- Validate on read: every record has a CRC and a sequence number (or a version); a record with a bad CRC was interrupted and is ignored, falling back to the previous one.
- Commit with a final write: write the data, then write a small "valid" marker last. A record without the marker is incomplete.
- Two copies (A/B): keep two slots and alternate; at boot, use the newest valid one.
- Brown-out detection: configure the BOR threshold so the MCU resets before the supply falls below the flash's minimum programming voltage, and avoid starting long erases when the battery is low.
Using internal flash safely
- Erase and program only through the vendor's procedure: unlock the flash controller, set parallelism and wait states, check error flags (programming, alignment, write protection), lock it again.
- Run flash-writing code from RAM, or use a dual-bank part and write to the other bank, so interrupts and code fetch continue.
- Keep the data region away from the code: reserve sectors in the linker script so a growing firmware cannot overwrite settings, and settings writes cannot hit code.
- On parts with ECC flash, a double-word can be programmed only once between erases; writing it twice raises an error.
Pitfall: Many STM32 parts have large sectors (16 KB to 128 KB) in the main flash bank. Using one for settings means every update erases up to 128 KB and stalls the CPU for a second or more. Pick a part or region with small pages, an external EEPROM or FRAM, or batch updates.
Interview question: How would you store device settings in internal flash so a power cut never corrupts them?
Answer: Reserve two or more small flash pages for settings in the linker script. Store settings as records with a version or sequence number and a CRC, appended to the active page rather than rewritten in place. On boot, scan for the newest record with a valid CRC. When the page fills, copy the newest record to the other page, verify it, and only then erase the old page. A power cut at any point leaves at least one valid, complete record, and wear is spread over many writes per erase. Use brown-out detection so writes do not happen at too low a voltage.
Interview question: Why can the CPU stall while writing internal flash, and how do you avoid it?
Answer: On single-bank flash the memory cannot be read while it is being programmed or erased, so instruction fetches from flash stall until the operation finishes, which for an erase can be tens to hundreds of milliseconds, blocking interrupts too. Avoid it by running the flash routines and any interrupt handlers that must keep working from RAM, using a dual-bank part that can read one bank while writing the other, or moving frequently written data to external memory.
Build it: a flight log that survives a power cut
This is step 1 of the module project, a flight data recorder for a delivery drone. After a crash, investigators need the last records before impact, but a crash also cuts the power, often in the middle of a write. The log has to survive that.
Lab: A power-cut-safe log in internal flash
The recorder keeps its log in 512 bytes of the microcontroller's own flash, split into 42 slots of 12 bytes. Flash behaves differently from RAM: erased flash reads 0xFF, and programming can only turn bits from 1 to 0, so a slot can be written only once until the whole area is erased. The flash driver is already written: flash_read, flash_program (whole 4-byte words) and flash_erase_all.
A slot holds one record: 8 bytes of data, then a 4-byte commit word. Write the data first and the commit word 0x5AA5F00F last. If the power fails half-way, the commit word is missing and the record can be recognised as torn.
| Slot state | How to recognise it |
|---|---|
| free | all 12 bytes are 0xFF |
| valid | the commit word is 0x5AA5F00F |
| torn | anything else: skip it, never reuse it |
journal_open()runs at power-up. It scans the slots, remembers the first free one (records are always written in order, so everything after it is free too) and returns how many valid records there are.journal_append(r)writes a record into the next free slot and returns true, or returns false when there is none left.journal_read(i, out)copies thei-th valid record (counting from 0, torn slots skipped) and returns true, or returns false if there are not that many.
Going deeper
Interview question: How would you store a greenhouse controller's settings so the memory does not wear out?
Answer: Write only when a setting actually changes, never on a timer, and estimate the worst-case writes over the product's life against the memory's endurance. If that is too many, rotate the record across several slots with a sequence number, or use a small log-structured store on flash. Protect each record with a CRC and keep the previous copy until the new one is verified.
Interview question: What is the difference between NOR and NAND flash, and where is each used?
Answer: NOR flash allows random byte reads and execute-in-place, has small erase sectors and high reliability, and is used for firmware (internal MCU flash, external SPI/QSPI NOR). NAND flash is denser and cheaper per bit, reads and writes in pages, erases in large blocks, ships with bad blocks and needs ECC and a flash translation layer; it is used for large storage, usually hidden behind a controller in SD cards, eMMC and SSDs, or managed with UBI on Linux.
Interview question: How does FRAM differ from flash for embedded logging?
Answer: FRAM writes bytes in place at bus speed with no erase cycle, uses very little energy per write, and has endurance of around 10^12 to 10^14 cycles, so high-rate logging and frequently updated counters need no wear levelling. Its drawbacks are lower density and higher cost per bit, so it suits kilobytes to a few megabytes of frequently changing data rather than bulk storage.
Explain it: In your own words, explain why updating a single byte in flash is risky and what pattern avoids the risk.
Answer: Flash can only clear bits when programming; setting any bit back to one requires erasing a whole page or sector. So changing one byte in place means reading the sector, erasing it and writing it all back, and a power failure between the erase and the end of the write loses every byte in that sector, while repeated erases also wear the flash out. The safe pattern is never to overwrite in place: append a new copy of the record, with a sequence number and CRC, to free space, use the newest valid copy on boot, and erase old space only after a newer valid copy exists elsewhere.