Merge pull request #7 from TomWS1/writeBytes-Update

Removed 256 restriction from writeBytes()
This commit is contained in:
Felix Rusu 2015-02-07 21:37:54 -05:00
commit 924c265cef
1 changed files with 24 additions and 11 deletions

View File

@ -6,6 +6,8 @@
* Minimal modifications should allow chips that have different page size but modifications * Minimal modifications should allow chips that have different page size but modifications
* DEPENDS ON: Arduino SPI library * DEPENDS ON: Arduino SPI library
* *
* Updated Jan. 5, 2015, TomWS1, modified writeBytes to allow blocks > 256 bytes and handle page misalignment.
*
* This file is free software; you can redistribute it and/or modify * This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2 * it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as * or the GNU Lesser General Public License version 2.1, both as
@ -185,20 +187,31 @@ void SPIFlash::writeByte(long addr, uint8_t byt) {
unselect(); unselect();
} }
/// write 1-256 bytes to flash memory /// write multiple bytes to flash memory (up to 64K)
/// WARNING: you can only write to previously erased memory locations (see datasheet) /// WARNING: you can only write to previously erased memory locations (see datasheet)
/// use the block erase commands to first clear memory (write 0xFFs) /// use the block erase commands to first clear memory (write 0xFFs)
/// WARNING: if you write beyond a page boundary (or more than 256bytes), /// This version handles both page alignment and data blocks larger than 256 bytes.
/// the bytes will wrap around and start overwriting at the beginning of that same page ///
/// see datasheet for more details
void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) { void SPIFlash::writeBytes(long addr, const void* buf, uint16_t len) {
command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program int n;
SPI.transfer(addr >> 16); int maxBytes = 256-(addr%256); // force the first set of bytes to stay within the first page
SPI.transfer(addr >> 8); while (len>0)
SPI.transfer(addr); {
for (uint16_t i = 0; i < len; i++) n = (len<=maxBytes) ? len : maxBytes;
SPI.transfer(((byte*) buf)[i]);
unselect(); command(SPIFLASH_BYTEPAGEPROGRAM, true); // Byte/Page Program
SPI.transfer(addr >> 16);
SPI.transfer(addr >> 8);
SPI.transfer(addr);
for (uint16_t i = 0; i < n; i++)
SPI.transfer(((byte*) buf)[i]);
unselect();
addr+=n; // adjust the addresses and remaining bytes by what we've just transferred.
buf +=n;
len -= n;
maxBytes = 256; // now we can do up to 256 bytes per loop
}
} }
/// erase entire flash memory array /// erase entire flash memory array