Simvik

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+58

A short write across one boundary

show(0xF0, 0x20);

Expected output:

2: F0+10 100+10

Learn it first

More SPI flash and SD cards problems