SPI flash command frame
Build the opcode and address bytes for a serial NOR flash command. An easy embedded C problem (SPI flash and SD cards), run and graded in the browser.
easy · SPI flash and SD cards · spi · nor-flash · byte-order
Serial NOR flash commands start with a one-byte opcode followed by the address, most significant byte first. Flash up to 16 MB uses 3 address bytes; larger parts use 4-byte addressing.
Write nor_frame(op, addr, four_byte, out): write the opcode and then 3 or 4 address bytes into out, and return the number of bytes written. With 3-byte addressing, only the low 24 bits of addr are sent.
Starter code
int nor_frame(uint8_t op, uint32_t addr, bool four_byte, uint8_t *out) {
out[0] = op;
out[1] = addr & 0xFF;
out[2] = (addr >> 8) & 0xFF;
out[3] = (addr >> 16) & 0xFF;
return 4;
}Example tests
Read and page program
show(0x03, 0x012345, false);
show(0x02, 0xABCDEF, false);Expected output:
03 01 23 45
02 AB CD EF4-byte addressing
show(0x13, 0x01ABCDEF, true);Expected output:
13 01 AB CD EFLearn it first
- SPI flash and SD cards · Serial NOR commands, the page boundary trap, and SD card bring-up in SPI mode.
More SPI flash and SD cards problems
- Split a write at page boundaries · Turn one write into page program commands that never cross a 256-byte page.
- Fix: every 256th byte is wrong · Data written to SPI flash reads back wrong at every page start after the first.