Try Embedded

SPI flash and SD cards

Serial NOR commands, the page boundary trap, and SD card bring-up in SPI mode.

Storage on the SPI bus

When internal flash is too small for logs, audio, images or a second firmware image, the usual answer is an external chip on SPI: a serial NOR flash (the W25Q, MX25 and GD25 families, 1 to 128 MB, soldered on the board) or an SD card (gigabytes, removable). Both talk SPI, but they behave very differently, and drivers for both have well-known traps.

Serial NOR flash: the command set

Almost every serial NOR chip uses the same commands, inherited from early Winbond and Macronix parts:

CommandByteWhat it does
Read JEDEC ID0x9FManufacturer and capacity: the first thing to read when bringing up a board
Read data0x03Address (3 bytes), then read as many bytes as you like, across pages
Fast read0x0BThe same with a dummy byte, for higher clock rates
Write enable0x06Must come before every program or erase
Page program0x02Address, then 1 to 256 bytes into one page
Sector erase0x20Erase 4 KB to all 0xFF
Block erase0xD8Erase 64 KB (faster per byte)
Read status0x05Bit 0 = BUSY (write in progress), bit 1 = WEL (write enable latch)

Each command is one chip-select-low transaction. A typical write is: write enable, page program, then poll status until BUSY clears. Page programs take about 0.5 ms, a 4 KB sector erase 50 to 400 ms, and a chip erase can take a minute or more.

The page boundary trap

A page program can only write within one 256-byte page. If the data runs past the end of the page, the chip does not continue into the next one: the address wraps to the start of the same page and overwrites it. A driver must split every write at page boundaries:

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define PAGE 16                 /* 256 on real chips; small here so the output fits */
static uint8_t chip[64];        /* a pretend flash chip, erased to 0xFF */

/* What the chip itself does with one Page Program command. */
static void chip_page_program(uint32_t addr, const uint8_t *src, uint32_t n) {
  uint32_t page_start = addr - addr % PAGE;
  for (uint32_t i = 0; i < n; i++) {
    uint32_t a = page_start + (addr - page_start + i) % PAGE;   /* wraps inside the page! */
    chip[a] &= src[i];          /* programming can only clear bits */
  }
}

/* A correct driver: never cross a page boundary in one command. */
static void flash_write(uint32_t addr, const uint8_t *src, uint32_t n) {
  while (n > 0) {
    uint32_t room = PAGE - addr % PAGE;          /* bytes left in this page */
    uint32_t chunk = n < room ? n : room;
    /* real code: write_enable(); page_program(...); wait_while_busy(); */
    chip_page_program(addr, src, chunk);
    addr += chunk; src += chunk; n -= chunk;
  }
}

static void dump(const char *label) {
  printf("%-8s", label);
  for (int i = 0; i < 32; i++) printf("%c", chip[i] == 0xFF ? '.' : chip[i]);
  printf("\n");
}

int main(void) {
  const char *msg = "HELLO-WORLD";            /* 11 bytes written at address 10 */

  memset(chip, 0xFF, sizeof chip);
  chip_page_program(10, (const uint8_t *)msg, 11);   /* one command, crossing the boundary */
  dump("naive:");

  memset(chip, 0xFF, sizeof chip);
  flash_write(10, (const uint8_t *)msg, 11);
  dump("split:");
  return 0;
}

The naive write puts the end of the message at the start of page 0, quietly corrupting whatever was there.

Other NOR rules worth knowing

  • Erase before write, in 4 KB sectors; programming can only turn 1s into 0s (see flash, EEPROM and FRAM).
  • Write enable resets itself after every program or erase. Forgetting it means the command is silently ignored: check the WEL bit when a write "does nothing".
  • Write protection: status register bits (BP0..BP2) can protect regions, and some boards hold the /WP pin low. A chip that ignores every erase often has protection set.
  • Power-down: deep power-down (0xB9) cuts the standby current from tens of µA to about 1 µA; release with 0xAB. Remember to wake it before the next command.
  • Quad SPI and XIP: in quad mode, four data lines raise throughput, and many MCUs can map the flash into the address space and execute code from it directly (execute in place).

SD cards in SPI mode

An SD card has its own controller, flash translation layer and wear levelling. You speak to it in 512-byte blocks, using 6-byte commands with a CRC. Bring-up has a fixed sequence:

  1. With the clock at 400 kHz or less and chip select high, send at least 74 clock pulses (10 bytes of 0xFF).
  2. CMD0 (GO_IDLE_STATE) with CS low: the card enters SPI mode and answers R1 = 0x01 (idle). CMD0 needs a valid CRC, 0x95.
  3. CMD8 (SEND_IF_COND) with argument 0x1AA: a version 2 card echoes 0x1AA. Its CRC is 0x87. An "illegal command" answer means an old version 1 card.
  4. Repeat ACMD41 (CMD55 then CMD41, with the HCS bit set) until the card answers 0x00, which can take up to a second.
  5. CMD58 reads the OCR: the CCS bit says whether the card is high capacity (SDHC/SDXC), which addresses blocks, or standard capacity, which addresses bytes.
  6. Raise the clock (to 20 or 25 MHz) and use CMD17/CMD24 to read or write one block, CMD18/CMD25 for several.

After CMD24, the card holds MISO low while it programs. Writes usually take a millisecond but can stall for hundreds of milliseconds while the card erases internally, so never write to an SD card from a time-critical context. Buffer data in RAM and write it from a low-priority task.

Serial NOR flashSD card
Capacity1 to 128 MBGigabytes
Unit of erase4 KB sectorHidden by the card
Wear levellingYours (or LittleFS)Built in, of unknown quality
Power-loss safetyYours to designVaries; cheap cards can corrupt on power loss
Write latencyPredictableUsually fast, sometimes very slow
SuitsFirmware images, configuration, moderate logsLarge logs, files a PC must read (FAT)

Pitfall: Several devices sharing a bus with an SD card: the card may keep driving MISO after CS rises until it sees one more clock byte. Send a 0xFF byte after raising CS, or the next device's reply is garbled.

Interview question: How do you initialise an SD card in SPI mode?

Answer: With chip select high and a slow clock, around 400 kHz, I send at least 74 clocks. Then CMD0 with its CRC 0x95 puts the card in SPI idle state, answered with 0x01. CMD8 with 0x1AA checks for a version 2 card. I repeat CMD55 plus ACMD41 with the high-capacity bit until the card answers 0x00, with a timeout of about a second. CMD58 reads the OCR to know whether it is high capacity, so addressed in blocks, or standard, addressed in bytes. Then I raise the clock and read or write 512-byte blocks with CMD17 and CMD24, waiting for the busy signal after writes.

Build it: a driver for the external SPI flash

This is step 3 of the module project. Internal flash holds only the last few records, so each whole flight is also stored on a 4 MB serial NOR flash chip on SPI. You write its driver: the commands every W25Q-style chip shares.

Lab: Erase, program and read a serial NOR flash

The chip is on SPI1, selected by PA4. The SPI and chip select helpers are already written. Each command is one chip-select transaction: pull it low, send the command byte (and a 24-bit address, most significant byte first, where there is one), move the data, raise it.

CommandByteNotes
JEDEC ID0x9Fthree bytes come back: maker, type, capacity
read status0x05bit 0 BUSY: an erase or program is still running
write enable0x06needed before every erase and program; the chip clears it after each
read0x03address, then as many bytes as you clock
page program0x02address, then up to 256 bytes, within one 256-byte page
sector erase0x20address: the 4 KB sector around it becomes 0xFF
  • flash_id() returns the three ID bytes as one number, first byte highest: 0xEF4016.
  • flash_wait() reads the status register until BUSY is clear. An erase takes far longer than a program, and the chip ignores every other command until it is done.
  • flash_erase_sector(addr) enables writing, erases the sector and waits.
  • flash_write(addr, data, n) programs n bytes, split at page boundaries: bytes past the end of a page would wrap to its start and overwrite the beginning. Each piece needs its own write enable and wait.
  • flash_read(addr, buf, n) reads n bytes.

The chip reports each erase and program, such as flash: program 0x001000 (16 bytes), and every mistake it would punish on a real board.

Going deeper

Interview question: How would you store a dashcam's video so it survives a power cut in a car?

Answer: Write video in fixed-size segments to the SD card with a file system tuned for it, preallocate files, and keep metadata updates rare. Detect power loss early (the ignition signal and a supply monitor) and use a hold-up capacitor to finish the current segment. Keep settings and crash records in SPI flash, separate from the bulk data.

Interview question: Why do SD cards sometimes take hundreds of milliseconds for one write, and how should firmware cope?

Answer: The card's controller maps logical blocks onto large physical erase blocks and occasionally has to erase, copy or garbage-collect them, which stalls the write. Firmware should not write from interrupt handlers or high-priority tasks: it buffers data in RAM, sized for the longest expected stall at the data rate, and writes from a low-priority task, ideally in large aligned chunks such as whole clusters. Monitoring buffer high-water marks shows whether the margin is enough.

Interview question: What is execute in place (XIP) and what are its costs?

Answer: XIP maps an external quad or octal SPI flash into the MCU's address space, so the CPU fetches instructions directly from it as if it were internal flash, allowing much larger programs. Each cache miss needs a SPI transaction, which is far slower than internal flash, so performance depends on the cache. Code that must run while the flash is being written or erased, such as the flash driver itself or time-critical interrupt handlers, has to run from RAM, because the flash cannot be read during a program or erase.

Explain it: In your own words, explain why a flash driver must split writes at page boundaries.

Answer: A Page Program command can only write inside one page, usually 256 bytes. The chip keeps an address counter that wraps around to the start of the same page when it reaches the end, instead of moving to the next page. So if a write starts near the end of a page and is longer than the remaining room, the extra bytes are written over the beginning of that page. The driver must therefore cut every write into pieces that each end at or before a page boundary, sending write enable and waiting for the busy flag for each piece.