/*****************************************************************************************/
//Program: Interfacing AT93C46A	serial EEPROM to a P89V51RD2 using the SPI//
/*****************************************************************************************/


#include <stdio.h>
#include <p89v51rx2.h>

unsigned char spi_transfer(unsigned char dat);
void delay(unsigned char Delval);
void delay_ms(unsigned int Delval_ms);

// Opcodes for controling the EPROM

#define EWEN 0x98
#define ERASE 0xe0
#define WRITE 0xa0
#define READ 0xc0

unsigned char ADDRESS = 0x01; //Memory Address
unsigned char DATA_1 = 0x25; // Data to be written to the memory
unsigned char read_data = 0x00;	//Data to be read from the memory

//SPI Pin Defination 
sbit cs = P1^4;
sbit di = P1^5;
sbit dou = P1^6;
sbit clk = P1^7;

//Debugging LEDs
sbit LED1 = P2^0;
sbit LED2 = P2^1;

//SPI READ and WRITE Function
unsigned char spi_transfer(unsigned char dat)
{
   SPDAT = dat;
   while (!(SPCFG & 0x80));
   SPCFG = 0x00;
   read_data = SPDAT;
   LED1 = 1; //LED1 used to check if the spi_transfer function is completely executed
   return(read_data);
   
}

//DELAY FUNCTIONS
//delay(10) = 200usec.

void delay(unsigned char Delval)
{
 unsigned char i=25;
 for(;Delval!=0;Delval--)
  for(;i!=0;i--);
}
 
void delay_ms(unsigned int Delval_ms)
{
 for(;Delval_ms!=0;Delval_ms--)
 {
  delay(250);
  delay(250);
  delay(250);
  delay(250);
 }
}
//MAIN
void main(void)
{

      unsigned char DATA_1 = 0x25; 
      unsigned char ret_dat = 0;
	
	LED1 = 0;
	LED2 = 0;

	cs = 1;
	di = 1;
	dou = 1;
	clk = 1;
	   
       SPCTL = 0x73; //initialize SPI
       cs = 0;
       delay_ms(10);
	   cs = 1;
	   spi_transfer(ERASE);
	   spi_transfer(ADDRESS);
       cs = 0;
       delay_ms(10);
	   
	   cs = 1;
       spi_transfer(EWEN); //enable write of eeprom
       cs = 0;
       delay_ms(10);

       cs = 1;
       spi_transfer(WRITE); //write sample data to the memory
       spi_transfer(ADDRESS);
       spi_transfer(DATA_1); 
       cs = 0;
       delay_ms(10);

     cs = 1;
     spi_transfer(READ); //read the data that is written at previous address
     spi_transfer(ADDRESS);
     ret_dat = read_data;
     cs = 0;
     delay_ms(10);
   
   //Check if all above operations are performed as desired
   if(ret_dat == DATA_1)
  {	
     LED2 = 1;
  }
  else    
 {
    LED2 = 0;
 } 
 while(1);

}

