#include <p18cxxx.h>
#include "Remote_Control_Sony.h"


unsigned int Buffer[26], index=0, Timeout=RC_TIMEOUT;
unsigned char New_Flag = 0;
struct Sony_Code Signal = {0, 0};

/*
#pragma code HIGH_INTERRUPT_VECTOR = 0x08
#pragma interrupt YourHighPriorityISRCode
void YourHighPriorityISRCode()
{
	static int index=0;



	//if (INTCON3 & 0x01)
	if (INTCON3bits.INT1IF)
	{
		// +++  Interrupt Code  +++
		
		Buffer[index] = TMR1L;
		Buffer[index] = Buffer[index] |  ((unsigned int)TMR1H<<8);
		index++;
		T1CONbits.TMR1ON = 0;
		TMR1H = 0x00;
		TMR1L = 0x00;
		
		T1CONbits.TMR1ON = 1;
		INTCON2 = INTCON2 ^ 0x20;			// toggling interrupt event: on falling/rising edge

		
		if (index==26)
		{
			unsigned char Digits[12];
			char k, i;
			
			index = 0;
			New_Flag = 1;
			//INTCON3 = INTCON3 & (~0x08);	// INT1 enabled
			INTCON3bits.INT1IF = 0;			// INT1 flag cleared
			
			Signal.Data = 0;
			Signal.Address = 0;
			k = 0;
			if (Buffer[1] < 0x0C00)		// check for parasite edge
				return;
			for (i=3; i<=25; i=i+2)
			{
				if (Buffer[i] > 0x0300 && Buffer[i] < 0x0400)
					Digits[k++] = 0;
				else
					if (Buffer[i] > 0x0700 && Buffer[i] < 0x0800)
						Digits[k++] = 1;
					else
						break;		// parasite frequency
			}

			for (k=11; k>=7; k--)
				Signal.Address = (Signal.Address<<1) | Digits[k];
			for (k=6; k>=0; k--)
				Signal.Data = (Signal.Data<<1) | Digits[k];
			return;
		}
		// ---  Interrupt Code  ---
		
		// Clearing the Interrupt Flag
		//INTCON3 = INTCON3 & (~0x01);
		INTCON3bits.INT1IF = 0;
	}
	return;
}
*/

#pragma code
void DelayMs (volatile unsigned int Ms)
{
	volatile unsigned int x;
	while (Ms--)
		for (x=900; x; x--);
	return;
}

void IrDA_Init (void)
{
	Clock_Init ();
    GPIO_Init ();
    Receiver_Init ();
    Timer1_Init ();
    return;
}

// Clock initialize
void Clock_Init (void)
{
	OSCTUNEbits.PLLEN = 1;  		// Enable the PLL and wait 2+ms until the PLL locks before enabling USB module
	DelayMs (50);
	return;
}

void Timer1_Init (void)
{
	TMR1H = 0x00;
	TMR1L = 0x00;
	T1CON = 0x33;
	return;
}

void GPIO_Init (void)
{
	// Analog input/output --> general purpose input/output
	// All outputs set as GPIO
    ANCON0 = 0xFF;
    ANCON1 = 0xFF;
    INTCON2bits.RBPU = 0;
    return;
}

void Receiver_Init (void)
{
    RCON = RCON | 0x80;				// IPEN = 1;	interrupt priority enabled
    INTCON = INTCON | 0xC0;			// high and low priority interrupts enabled
    
	TRISC = TRISC | 0x80;			// PC7 - input
	RPINR1 = 18;					// INT1 function associated with pin 18
	DelayMs (1);
	INTCON3bits.INT1IF = 0;
	INTCON2 = INTCON2 & (~0x20);	// interrupt on falling edge
	INTCON3 = INTCON3 | 0x48;		// INT1 enabled as High priority interrupt
	return;
}

/*
void main ()
{
	unsigned char Digits[12];
	char k, i;
	for (i=0; i<100; i++)
		Buffer[i] = 0;
	IrDA_Init ();
	
	while (1)
	{
		if (New_Flag)
		{
			// do something with the signal
			New_Flag = 0;	// clear the flag
		}
	}
}
*/
