Go Down

Topic: Interfacing the 25A512-I/SN SPI EEPROM with the Arduino Mega (Read 1 time) previous topic - next topic

mondalaci

Hey guys,

I'm posting this because the official tutorial at http://arduino.cc/en/Tutorial/SPIEEPROM seems really convoluted.  Utilizing the SPI library makes things so much cleaner.

Code: [Select]

#include <SPI.h>

const byte COMMAND_WRITE_ENABLE = 0b110;
const byte COMMAND_WRITE_DATA = 0b10;
const byte COMMAND_READ_DATA = 0b11;

const byte chipSelectPin = 53;

void setup()
{
  Serial.begin(9600);

  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.setDataMode(SPI_MODE0);
  SPI.begin();

  Serial.println("Write enable");
  digitalWrite(chipSelectPin, LOW);
  SPI.transfer(COMMAND_WRITE_ENABLE);
  digitalWrite(chipSelectPin, HIGH);

  Serial.println("Writing data");
  digitalWrite(chipSelectPin, LOW);
  SPI.transfer(COMMAND_WRITE_DATA);
  SPI.transfer(0);  // First address byte
  SPI.transfer(0);  // Second address byte
  SPI.transfer(2);  // Write byte 1
  SPI.transfer(5);  // Write byte 2
  SPI.transfer(9);  // Write byte 3
  digitalWrite(chipSelectPin, HIGH);

  Serial.println("Reading data");
  digitalWrite(chipSelectPin, LOW);
  SPI.transfer(COMMAND_READ_DATA);
  SPI.transfer(0);  // First address byte
  SPI.transfer(0);  // Second address byte
  Serial.println(SPI.transfer(0), DEC);  // Read and print byte 1
  Serial.println(SPI.transfer(0), DEC);  // Read and print byte 2
  Serial.println(SPI.transfer(0), DEC);  // Read and print byte 3
  digitalWrite(chipSelectPin, HIGH
  );
}

void loop()
{
}


Enjoy!

Laci

Go Up