#include <LPC21xx.H>


void SPI_ISR (void) __irq;
void SPI_write(unsigned char *buffer,unsigned char bytecount);
void SPI_read(unsigned char *buffer,unsigned char bytecount);

unsigned char status 		= 0;
unsigned char SPI_bytecount = 0;
unsigned char * SPI_buffer;
volatile unsigned char lock = 0;
unsigned char input_buffer[8];
void main (void)
{
unsigned char output_buffer[8] = {1,2,3,4,5,6,7,8};



PINSEL0 		= 	0x00005500;			//Enable SPI0 pins
IODIR0 			= 	0x00000400;			//Enable Chipselect pin as output

S0SPCCR			=	;					//Set bit timing
S0SPCR   		=	;					//Configure as SPI Master interrupts enabled


VICVectCntl0 	= 	0x0000002A;  		//Select a priority slot for a given interrupt
VICVectAddr0 	= 	(unsigned)SPI_ISR;	//Pass the address of the IRQ into the VIC slot
VICIntEnable 	= 	0x00000400;			//Enable interrupt

SPI_write( );							//Write eight bytes to the memory
while(lock)
{
;
}
SPI_read(input_buffer,8);			  	//Read them back
IOCLR0 = input_buffer[0];

while(1)
{
;
}
}


void SPI_write(unsigned char *buffer,unsigned char bytecount)
{
lock = 1;
SPI_buffer 		= 	buffer;
SPI_bytecount 	= 	bytecount;
IOCLR0 			= 	0x00000400;			//Pull Chipselect low
S0SPDR 			= 	0x00000006;			//Send WRITE opcode
status			=	0x01;				//set next state
}

void SPI_read(unsigned char *buffer,unsigned char bytecount)
{
SPI_buffer 		= 	buffer;
SPI_bytecount 	= 	bytecount;
IOCLR0 			= 	0x00000400;			//Pull Chipselect low
S0SPDR 			= 	0x00000003;			//Send  READ code
status			=	0x05;				//set next state
}


void SPI_ISR (void) __irq
{
unsigned char result;
unsigned int test;

switch(status)
{
case (0x01): 
										//Send Write opcode
S0SPDR			=	;			
status			=	;					//set next state
break;

case (0x02):							//Send Write Address
S0SPDR			=	0x00000000;
status = 0x03;							//Set next state
break;

case (0x03):							//write data
S0SPDR			=	*SPI_buffer++;
if( --SPI_bytecount)
{
status = 0x03;							//Set Next state
}
else
{
status = 0x04;							//End condition
}
break;

case (0x04):							//End condition
S0SPDR				=	0x00000055;		//Need this dummy write for simulation
IOSET0 				= 	0x00000400;		//Pull Chipselect high
status				= 	0x07;			//jump to null case
break;
	 

case (0x05):
S0SPDR 			= 	0x00000000;			//Send Address
status			=	0x06;				//set next state
break;

case (0x06):
*SPI_buffer		= 	S0SPDR;				//read data
S0SPDR 			= 	0xFF;				//Send Address
SPI_buffer++;

if( --SPI_bytecount)
{
status = 0x06;							//Set Next state
}
else
{
status = 0x07;							//End condition
}
break;

case (0x07) :							//Null Case
lock = 0;
break;

default :
break;

}
				
S0SPINT 		= 	0x01;	 			//Signal end of interrupt
VICVectAddr 	= 	0x00000000;			//Dummy write to signal end of interrupt
}