Split a write at page boundaries
Turn one write into page program commands that never cross a 256-byte page. A medium embedded C problem (SPI flash and SD cards), run and graded in the browser.
medium · SPI flash and SD cards · spi · nor-flash · page-program
A NOR flash page program command can write at most to the end of the current 256-byte page. If it goes further, the address wraps to the start of the same page and overwrites data there.
Write nor_split(addr, len, out): split a write of len bytes starting at addr into chunks that each stay inside one page, in order, store them in out, and return how many there are.
Starter code
int nor_split(uint32_t addr, uint32_t len, chunk_t *out) {
int n = 0;
while (len > 0) {
uint32_t part = len < PAGE ? len : PAGE;
out[n].addr = addr;
out[n].len = part;
n++;
addr += part;
len -= part;
}
return n;
}Example tests
Aligned start
show(0x100, 600);Expected output:
3: 100+100 200+100 300+58A short write across one boundary
show(0xF0, 0x20);Expected output:
2: F0+10 100+10Learn 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
- SPI flash command frame · Build the opcode and address bytes for a serial NOR flash command.
- Fix: every 256th byte is wrong · Data written to SPI flash reads back wrong at every page start after the first.