#include <hidef.h>      /* common defines and macros */
#include "derivative.h"      /* derivative-specific definitions */

volatile unsigned int spi0_data_in; 
volatile unsigned int *ptr_g;                       //global pointer to data
volatile unsigned int packet_lenght;
//==============================================================================
//SPI0 interrupt runtine
//==============================================================================
#pragma CODE_SEG NON_BANKED
interrupt 19 void SPI0_Isr(void)       
{ 
 
//******************************************************************************
//Interrupt runtine RECEIVER part
//******************************************************************************

//if receiver interrupt is enabled and corresponding interrupt flag is set
 if(SPI0SR & (SPI0SR_SPIF_MASK | SPI0SR_MODF_MASK))
  {
    if(SPI0SR & SPI0SR_MODF_MASK)            // if overrun error do nothing/something
      {
        (void)SPI0DRL;                            // clear interrupt flag 
        // do something
      }
    else
      {
        spi0_data_in = SPI0DR;             // read received character + clear interrupt flag
        //---------------
        while(!SPI0SR_SPTEF);              //wait for transmit data register empty flag
        SPI0DR = spi0_data_in + 0xF000;    //return value back + offset
        
      }
  }
  
 
 
//******************************************************************************
//Interrupt runtine TRANSMITTER part
//******************************************************************************

  //if tranceiver interrupt is enabled and corresponding interrupt flag is set
  if((SPI0CR1 & SPI0CR1_SPTIE_MASK) && ((SPI0SR & SPI0SR_SPTEF_MASK)))
  { 
    SPI0DR = *ptr_g;                           //Send data
    *ptr_g++;
    packet_lenght--;
    
    if (packet_lenght == 0)                     //end of packet detection
          {
            SPI0CR1_SPTIE = 0;                  //Tx interrupt requests disabled
          }
    
  }
  
}
#pragma CODE_SEG DEFAULT


//==============================================================================
// SPI0 setup	- Slave																				
//==============================================================================
static void setupSPI0(void)
{
 // PTS     = 0xF0;                          // Set default state of SPI pins when SPI not active; PS4,5,6,7 
 // DDRS    = 0xF0;

  SPI0CR1 = 0B11000000;                      // SPIE SPE SPTIE MSTR CPOL CPHA SSOE LSBFE
  SPI0CR2 = 0B01000000;                      // x XFRW x MODFEN BIDIROE x SPISWAI SPC0
  //SPI0BR  = 0x07;                            // 31.25kHz for Bus = 8MHz / ((0+1)* 2^(7+1)) = 31.25MHz;
}

void main(void) {
  /* put your own code here */
  
  setupSPI0();

	EnableInterrupts;


  for(;;) {
    _FEED_COP(); /* feeds the dog */
  } /* loop forever */
  /* please make sure that you never leave main */
}
