---
title: Keeping data through power-off
heading: Flash, wear and records that survive a power cut
eyebrow: C12 · Lesson 43 · Keeping data through power-off
xp: 40
---

::: hook
A thermostat that forgets its schedule at every power cut, or a logger whose last hour of data is garbage, has a storage problem. Microcontrollers keep data in **flash**, the same memory that holds the program, and flash has rules that RAM doesn't: it erases only in large sectors, a write can only clear bits, an erase takes milliseconds, and each sector survives only a limited number of erases. Firmware that ignores those rules works on the bench and dies in the field, worn out in a week or corrupted by an unlucky power cut. This lesson budgets wear and designs records that survive.
:::

::: play
- The curves are a device's flash lifetime in years against how often it saves a record, for two designs: erasing a sector for every save, and appending records to a log that's erased only when full.
- Raise the number of sectors the log rotates through: its lifetime grows in proportion. Lower the record size: more records fit before each erase.
- Note the vertical scale: the naive design wears out in days at one save a minute.
:::

```sim plot
view: graph
x: w = 1..1440 saves/day log
y: L = 0.001..1000 years log
slider: E = 1000..100000 = 10000 log
slider: n = 1..16 step 1 = 4
slider: r = 8..256 step 8 = 16 bytes
plot: E/w/365.25 | dashed | label: erase per save
plot: E*n*floor(4096/r)/w/365.25 | label: log of records
readout: log lifetime at one save a minute (years) = E*n*floor(4096/r)/1440/365.25 | digits: 3
```

::: predict
## Flash holds 0xF0 at an address. Without erasing, the program writes 0x3C there. What does it read back?

- [ ] 0x3C
- [ ] 0xFC
- [x] 0x30
- [ ] 0xF0, because the write is refused

::: reveal
Programming can only change 1s to 0s, so the result is the AND of the old and new values: 0xF0 AND 0x3C = 0x30. To store 0x3C the sector must be erased to 0xFF first. Many flash controllers don't report this; the data is simply wrong.
:::
:::

::: nameit
## How flash behaves

- **Erase** sets a whole sector (typically 1 to 4 KB on a microcontroller) to all 1s, 0xFF. It takes milliseconds.
- **Program** clears chosen bits to 0, a word or a page at a time, in tens of microseconds. Writing over data that isn't erased gives the AND of the two.
- **Endurance:** each sector survives roughly $10^4$ to $10^5$ erase cycles. **Retention:** data lasts 10 to 20 years, less when hot.
- While a sector of the same bank is erasing, the processor often can't run code from flash.

## Wear

If every save erases a sector, the sector lasts $E$ saves. A **log** appends fixed-size records to an erased sector and erases only when it's full, so a sector of $S$ bytes with $r$-byte records takes $\lfloor S/r\rfloor$ saves per erase, and rotating through $n$ sectors spreads the wear:
$$\text{saves} = E\,n\,\lfloor S/r\rfloor$$

## Surviving a power cut

A record is written in steps, and power can fail between any two. Give each record a **sequence number** and a **CRC**, and on startup take the newest record whose CRC is good; a half-written record fails its CRC and is ignored. Erase the oldest sector only after the next one holds a good copy. Firmware updates use the same idea: two image slots (A/B), switching only after the new image checks out.

## Hold-up

To finish an operation that's already started when power fails, a capacitor must supply it: from $V_1$ down to the lowest working voltage $V_2$, $E = \tfrac12 C(V_1^2 - V_2^2)$.
:::

::: example
## A device saves its settings once a minute to one 4 KB sector rated for 10,000 erases, erasing before each save. How long does the flash last? What if 16-byte records are appended to a log across 8 sectors?

::: solution
1. **Erasing before each save.** The sector lasts 10,000 saves, one a minute:
   $$10\,000\ \text{min} = 6.9\ \text{days}$$
2. **Records per erase.** As a log, the 4 KB sector takes 256 records of 16 bytes between erases.
3. **One sector as a log.**
   $$\begin{aligned} 10\,000 \times 256 &= 2.56 \times 10^6\ \text{min} \\ &= 4.9\ \text{years} \end{aligned}$$
4. **Eight sectors.** They last 39 years.
5. **Compare.** The same flash, written differently, lasts two thousand times longer.

**Answer:** 6.9 days erasing before each save, and 39 years as a log across 8 sectors.
:::
:::

::: example
## A sector erase takes 30 ms at 10 mA from 3.3 V, and the regulator drops out below 2.5 V. What hold-up capacitor lets an erase that has just started finish?

::: solution
1. **Energy for the erase.**
   $$\begin{aligned} E &= 3.3 \times 0.010 \times 0.030\ \text{J} \\ &= 0.99\ \text{mJ} \end{aligned}$$
2. **Capacitance to supply it.** The capacitor gives up that energy as it falls from 3.3 V to 2.5 V:
   $$\begin{aligned} C &= \frac{2E}{V_1^2 - V_2^2} \\ &= \frac{1.98 \times 10^{-3}}{10.89 - 6.25}\ \text{F} \\ &= 427\ \mu\text{F} \end{aligned}$$
   so a 470 µF part, more if the rest of the board keeps drawing current.
3. **A cheaper approach.** Records with CRCs are cheaper: they make an interrupted write harmless instead of trying to prevent it.

**Answer:** at least 427 µF, so a 470 µF part.
:::
:::

::: example
## Why can a log find its newest record without a separate "latest" pointer?

::: solution
1. **Number each record.** Each record carries a sequence number that only increases.
2. **Scan at startup.** The program scans the sectors, ignores erased slots (all 0xFF) and records with bad CRCs, and takes the record with the highest sequence number.
3. **Why not a pointer.** A pointer stored somewhere fixed would itself be rewritten on every save, wearing out the one sector the log was meant to protect.

**Answer:** each record carries a sequence number that only increases, so the newest is the valid record with the highest number.
:::
:::

::: check
kind: parts
given: E = 10000 | 100000; w = 1 | 60 | 1440

## A device erases a flash sector rated for {E} cycles every time it saves, {w} times a day.

::: part
answer: E/w
unit: days
tolerance: 0.5%

### How long does the sector last?

::: misses
- [any] Endurance ÷ saves per day.
:::
:::

::: part
answer: E/w/365.25
unit: years
tolerance: 0.5%

### In years?

::: misses
- [any] Days ÷ 365.25.
:::
:::
:::

::: check
kind: parts
given: E = 10000 | 100000; S = 1024 | 4096; r = 8 | 32 | 64; n = 2 | 8; w = 1440 | 86400

## Records of {r} bytes are appended to a log over {n} sectors of {S} bytes, each rated for {E} erases; the device saves {w} times a day.

::: part
answer: floor(S/r)
tolerance: 0

### How many records fit in a sector?

::: misses
- [any] $\lfloor S/r\rfloor$.
:::
:::

::: part
answer: E*n*floor(S/r)/w/365.25
unit: years
tolerance: 0.5%

### How long does the flash last?

::: misses
- [E*floor(S/r)/w/365.25] Rotating through {n} sectors multiplies it by {n}.
- [any] $E\,n\lfloor S/r\rfloor$ saves.
:::
:::
:::

::: check
kind: number
answer: 72
base: 16
width: 2

## Flash holds 0x5A. Without erasing, 0xC9 is programmed over it. What does it read back?

::: misses
- [201] Programming can't set bits that are already 0; the result is the AND.
- [any] The AND of the old and new values.
:::
:::

::: check
kind: parts
given: t = 20 | 50 | 400; I = 5 | 10 | 25; V = 2.5 | 2.8

## A sector erase takes {t} ms at {I} mA from 3.3 V; the system works down to {V} V.

::: part
answer: 3.3*I*t*1e-6*1000
unit: mJ
tolerance: 0.5%

### How much energy does the erase need?

::: misses
- [any] $VIt$.
:::
:::

::: part
answer: 2*3.3*I*t*1e-6/(3.3^2 - V^2)*1e6
unit: µF
tolerance: 0.5%

### What hold-up capacitance supplies it?

::: misses
- [2*3.3*I*t*1e-6/3.3^2*1e6] The capacitor can only fall to {V} V, not to zero.
- [any] $2E/(V_1^2 - V_2^2)$.
:::
:::
:::

::: check
kind: parts
given: M = 0.5 | 1 | 4; b = 16 | 64; s = 1 | 10; E = 10000 | 100000

## A logger writes {b}-byte records {s} times a second into a {M} MB circular log of flash rated for {E} erases.

::: part
answer: M*1048576/(b*s)/86400
unit: days
tolerance: 0.5%

### How long does the log take to fill once?

::: misses
- [M*1e6/(b*s)/86400] A megabyte of flash is 1,048,576 bytes.
- [any] Size ÷ (record size × rate).
:::
:::

::: part
answer: E*M*1048576/(b*s)/86400/365.25
unit: years
tolerance: 0.5%

### How long until the flash wears out, each sector erased once per lap?

::: misses
- [any] Endurance × lap time.
:::
:::
:::

::: check
kind: parts
given: K = 16 | 64 | 256; p = 256 | 512; t = 0.5 | 2; e = 4 | 16; d = 20 | 50

## A {K} KB image is written to flash in {p}-byte pages taking {t} ms each, after erasing {e} KB sectors that take {d} ms each.

::: part
answer: K*1024/p*t + K/e*d
unit: ms
tolerance: 0.5%

### How long does the whole update take?

::: misses
- [K*1024/p*t] Erase the sectors first.
- [any] Pages × page time + sectors × erase time.
:::
:::

::: part
answer: K/e*d/(K*1024/p*t + K/e*d)*100
unit: %
tolerance: 0.5%

### What share of it is erasing?

::: misses
- [any] Erase time over total.
:::
:::
:::

::: check
kind: order

## Put the steps of a power-safe settings save in order, writing to a log of records.

1. Build the record with the next sequence number
2. Compute its CRC
3. Program it into the next erased slot
4. Read it back and check the CRC
5. If the sector is now full, erase the oldest sector only after the next one holds a good copy

::: misses
- [any] Write and verify the new record before discarding any old one.
:::
:::

::: check
kind: python

## Write `program(old, new)`: flash bytes `old` programmed with `new` (lists of equal length) without erasing; return the bytes read back. Then `latest(records)`: each record is a dict with `seq`, `value` and `crc_ok`; return the `value` of the good record with the highest `seq`, or `None` if none is good.

```python starter
def program(old, new):
    return list(new)

def latest(records):
    return None
```

```python solution
def program(old, new):
    return [a & b for a, b in zip(old, new)]

def latest(records):
    good = [r for r in records if r['crc_ok']]
    if not good:
        return None
    return max(good, key=lambda r: r['seq'])['value']
```

```python tests
assert program([0xFF, 0xF0], [0x3C, 0x3C]) == [0x3C, 0x30], "Erased bytes take the value; others AND."
assert program([0x5A], [0xC9]) == [0x48], "0x5A AND 0xC9 = 0x48."
recs = [{'seq': 7, 'value': 'a', 'crc_ok': True}, {'seq': 9, 'value': 'b', 'crc_ok': False}, {'seq': 8, 'value': 'c', 'crc_ok': True}]
assert latest(recs) == 'c', "Record 9 was cut off mid-write: fall back to 8."
assert latest([{'seq': 1, 'value': 'x', 'crc_ok': False}]) is None, "No good record: None."
```

::: right
Right. Those two rules, AND on write and newest good record wins, are most of what makes flash storage dependable.
:::
:::

::: explain
## Why does appending records to a log, rather than erasing and rewriting one fixed location, both extend flash life and protect against power cuts?

::: model
Flash wears out by erasing, and an erase clears a whole sector at once. Rewriting a fixed location means an erase for every save, so the sector's ten thousand or so erases are used up quickly. Appending records to an erased sector uses one erase for hundreds of saves, and rotating through several sectors spreads the wear further. The log also never destroys the last good copy before writing the next: each new record goes into fresh space with a sequence number and a CRC, so if power fails partway through, the half-written record fails its check at startup and the previous record is still there to use.
:::
:::

::: practice
::: check
given: E = 3000 | 20000; w = 24 | 288
answer: E/w
unit: days
tolerance: 0.5%

## Days of life erasing a {E}-cycle sector {w} times a day?

::: misses
- [any] Endurance ÷ rate.
:::
:::

::: check
given: S = 2048 | 4096; r = 12 | 48
answer: floor(S/r)
tolerance: 0

## How many {r}-byte records fit in a {S}-byte sector?

::: misses
- [any] Round down.
:::
:::

::: check
given: t = 25 | 100; V = 2.2 | 2.7
answer: 2*3.3*0.01*t*1e-3/(3.3^2 - V^2)*1e6
unit: µF
tolerance: 0.5%

## Hold-up capacitor for {t} ms at 10 mA from 3.3 V down to {V} V?

::: misses
- [any] $2E/(V_1^2 - V_2^2)$.
:::
:::
:::
