Today I am posting the Spin object I wrote to interface to a Winbond W25X80 flash chip. The chip holds one megabyte (8mbits) and is very easy to use.
You can program up to 256 bytes at a time; however you have to be aware of a ‘gotcha’ – if you start programming at a byte that is not the first byte of the page, and go past the end of the 256 byte page, the internal programming pointer will wrap around and program at the start of the page.
Don’t worry, I included a (not very elegant) routine that hides the messy details, and will program more than 256 bytes in one method invocation.
To use the object, hook up the flash chip to four consecutive pins – if you hooked them up to P24-P27 then:
- SPI_CS would be P27
- SPI_CLK would be P26
- SPI_DO would be P25
- SPI_DI would be P24
In your Spin code, add the following to your OBJ section:
In your initialization section, add:
flash.init(24) ‘ if you are using pins P24-P27
All the routines take 24 bit addresses, in the lower 24 bits of a 32 bit long.
Let’s say you declare the following:
You can then read and write up to 4096 bytes at a time, with two simple calls:
Writing some data is just as simple!
One thing about flash chips – you can only erase specific block sizes, and not single bytes. In the case of the W25X80, you have three choices when erasing: 4Kbytes, 64Kbytes or the whole chip. You need to supply a starting address in all cases, however when you are using ‘Chip Erase’ the address will be ignored.
flash.write_en(1) ‘ enable erasing
flash.erase(starting_address,erase_size) ‘ 0 erases 4KB, 1 erases 64KB, 99 erases the chip
The call to flash.write_en(1) is needed to allow erasure; it is built into the write command so you don’t need it for simple writes.
The code is pretty generic, it should work with most SPI flash devices up to 128Mbits in size. You can actually get information about what flash chip is connected to your Propeller using the jdec_id method, and you can get the capacity of the device in bytes usig the get_size method.
Should you have any questions, feel free to comment on this thread here!