/***************************************************************************

 Author        : ADI - Apps                    www.analog.com/MicroConverter

 Date          : May. 2007

 File          : I2C_Slave.c

 Hardware      : Applicable to ADuC702x rev H or I silicon
                 Currently targetting ADuC7028.

 Description   : I2C Slave to demonstrate with I2C_Master.
				 
				 Operates in two modes, read & write (called recieve and 
				 transmit here). At the begining of an I2C transmission, the 
				 Master sends an address. The LSB of this address determines 
				 if the Master is to read (1) or write (0).

		
***************************************************************************/

#include<ADuC7028.h>

void My_IRQ_Handler(void);

typedef unsigned char       BYTE;       //8-bit
typedef unsigned short int  HALFWORD;   //16-bit
typedef unsigned int        WORD;       //32-bit


#define TRUE 1
#define FALSE 0
#define HIGH 1
#define LOW 0

short i = 0, dat[256];
int r = 0;
int w = 0;

BYTE i2c_first = TRUE;


int main()
{
	dat[0] = 0;
	dat[1] = 1;
	dat[2] = 2;
	dat[3] = 3;
	dat[4] = 4;
	dat[5] = 5;
	dat[6] = 6;
	dat[7] = 7;
	i=1;
	// I2C on P1.0 and P1.1
 	GP1CON = 0x22;

	IRQ=My_IRQ_Handler;
	IRQEN = 0x200;					// I2C0 Slave Interupt
	
	I2C0CFG = 0x4001;//0x01;		  			// Slave Enable
	I2C0ID0 = 0xA0;					// Slave ID
	I2C0STX = 0x77;
	
	
	while (1)
	{
	}; 

// 	return 0;
}



/*************************************************/
/*************************************************/
/************	IRQ Service Routine  *************/
/*************************************************/
/*************************************************/


unsigned int status;
unsigned int x;
unsigned int addr;


void My_IRQ_Handler()
{
	
	status = I2C0SSTA;
	if (((status & 0x02000)==0x02000))   // Slave Transmit IRQ
	{		 
		 r=0;
		 w=-1;
		 i++;		
	}
	// Slave Recieve
	if ((status & 0x08)==0x08)   // Slave Recieve IRQ
	{
		if(w==-1){
	 	   addr = I2C0SRX;
		   w++;
		}
		else{
		/*	if(w==0){

			}
			else if(w==1){

			}*/
			dat[addr+w] = I2C0SRX;
			w++;
		} 
		//I2C0STX = dat[addr+r];
		//I2C0STX = dat[addr+r];
		 
		   //i++;
	}

	
	// Slave Transmit
	if ((status & 0x04)==0x04)   // Slave Transmit IRQ
	{		 
		 I2C0STX = dat[addr+r];
		 //I2C0STX = dat[addr+r];
		 r++;
	//	 i++;		
	}

	
	//i++;


}

