Simvik

Split a flash write at page boundaries

Cut a write into Page Program commands that never cross a page. A medium embedded C problem (SPI), run and graded in the browser.

medium · SPI · spi · flash · storage

A serial NOR flash's Page Program command writes inside one page only. If a write runs past the end of the page, the chip wraps to the start of the same page and overwrites it.

Write page_chunks(addr, len, page, starts, lens): split a write of len bytes at addr into chunks that each stay inside one page (page is the page size, a power of two). Store each chunk's start address and length in order, and return the number of chunks. A write of 0 bytes has no chunks.

Starter code

int page_chunks(uint32_t addr, uint32_t len, uint32_t page, uint32_t *starts, uint32_t *lens) {
  int n = 0;
  while (len > 0) {
    uint32_t chunk = len < page ? len : page;
    starts[n] = addr; lens[n] = chunk; n++;
    addr += chunk; len -= chunk;
  }
  return n;
}

Example tests

Inside one page

show(0x100, 32, 256);

Expected output:

1 chunk: 0x100+32

Crossing one boundary

show(0x10F0, 100, 256);

Expected output:

2 chunks: 0x10F0+16 0x1100+84

Learn it first

  • SPI · Clock modes, chip select, multiple devices and throughput.

More SPI problems