Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SPI.h>
- #define READ 0x03 //read command
- #define WRITE 0x02 //write command
- #define WREN 0x06 // write enable
- const int csPin = 10;
- const int wpPin = 9; // For this sketch you could also leave the wpPin unconnected
- const int writeCycle = 10;
- void setup(){
- pinMode(csPin, OUTPUT);
- digitalWrite(csPin, HIGH);
- pinMode(wpPin, OUTPUT);
- digitalWrite(wpPin,HIGH);
- SPI.begin();
- Serial.begin(9600);
- eepromWriteEnable();// enable write enable latch bit
- digitalWrite(csPin, LOW);
- SPI.transfer(0x60); //chip erase command
- digitalWrite(csPin, HIGH);
- delay(8000); //max time taken for chip erase to process
- int intToWrite = 42;
- eepromWriteInt(4, intToWrite);
- intToWrite = -1111;
- eepromWriteInt(6, intToWrite);
- int intToRead = 0;
- intToRead = eepromReadInt(4);
- Serial.print("intToRead (Address = 4): ");
- Serial.println(intToRead);
- intToRead = 0;
- intToRead = eepromReadInt(6);
- Serial.print("intToRead (Address = 6): ");
- Serial.println(intToRead);
- }
- void loop(){}
- void eepromWriteEnable(){
- digitalWrite(csPin, LOW);
- SPI.transfer(WREN); //set write enable latch
- digitalWrite(csPin, HIGH);
- }
- void eepromWriteInt(int addr, int value){
- eepromWriteEnable();
- delay(100);
- // If you want to change the SPI clock speed, uncomment the following line and adjust
- SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
- digitalWrite(csPin, LOW);
- SPI.transfer(WRITE); //write command
- SPI.transfer((byte)(addr>>16)); //1st byte of 2 byte address
- SPI.transfer((byte)(addr>>8));
- SPI.transfer((byte)(addr&0xFF)); //1nd byte of 3 byte address
- SPI.transfer((byte)(value>>16)); //2st byte of 3 byte data
- SPI.transfer((byte)(value>>8));
- SPI.transfer((byte)(value&0xFF));//3nd byte of 3 byte data
- digitalWrite(csPin, HIGH);
- SPI.endTransaction(); // Uncomment if you have uncommented SPI.beginTransaction()
- delay(writeCycle);
- }
- int eepromReadInt(int addr){
- byte MSB = 0;
- byte LSB = 0;
- int value = 0;
- SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
- digitalWrite(csPin, LOW);
- SPI.transfer(READ);
- SPI.transfer((byte)(addr>>16)); //1st byte of 3 byte address
- SPI.transfer((byte)(addr>>8));
- SPI.transfer((byte)(addr&0xFF));
- MSB = SPI.transfer(0x00); //store the first byte in MSB buffer
- LSB = SPI.transfer(0x00); //store the first byte in LSB buffer
- digitalWrite(csPin, HIGH);
- SPI.endTransaction();
- value = (int)((MSB<<8)|LSB);
- return value;
- }
Advertisement
Add Comment
Please, Sign In to add comment