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+32Crossing one boundary
show(0x10F0, 100, 256);Expected output:
2 chunks: 0x10F0+16 0x1100+84Learn it first
- SPI · Clock modes, chip select, multiple devices and throughput.
More SPI problems
- What an SPI mode means · Turn an SPI mode number into the clock's idle level and the edge that samples data.
- Feed a daisy chain · Send bytes to a chain of 74HC595s so each chip shows its own pattern.
- Read registers in a burst · Read several registers with one command, setting the read bit and skipping the command's reply.
- Driver: bring up SPI and read a sensor's ID · Configure an SPI master and its chip-select pin, then read one register from a sensor.
- Driver: read an accelerometer in one burst · Power a sensor up over SPI and read its three axes in one chip-select assertion.
- Fix: the sensor ignores its configuration · A register write releases chip select while the last byte is still being clocked out.
- Smartwatch: pixels for the display · Pack a 24-bit colour into the display's 16-bit RGB565 format, in the order SPI sends it.