#include "rem.h"
void REM_def(void);
void REM_num(void);
//Midea
uint8_t xdata ON_R[6] = {0xB2, 0x4D, 0x1F, 0xE0, 0x48, 0xB7};
uint8_t xdata OFF_R[6] = {0xB2, 0x4D, 0x7B, 0x84, 0xE0, 0x1F};
//
extern uint8_t KEY;
extern uint8_t TEMP;
extern uint8_t IDLE_FLG;
uint8_t * ADD;
uint8_t bz = 0; //编码状态标志位
uint8_t i = 0, j = 0 , k = 0;


void rem_init(void)
{
	P5CR = 0xFF;
	P5 = 0xFF;
	CLKEN0 = 0x38;
	CLKEN1 = 0x30;	
	ALFSEL1 = 0x80; //PWM1  P5.4
	SYSCON |= 0x01;
	while((CLKSTAT & 0x01) == 0);
	SYSCON |= 0xC0;
	CKCON = 0x00;
	CLKCFG &= ~0x80;
	REMCON = 0x01; //REM输出
	EA = 1;
	
	PWM0CON = 0x45; //低电平驱动，选择REM功能，选择系统时钟4MHZ
	PWM0P = 0x69; //设置载波频率为38KHZ
	PWM0D = 0x45; //设置载波占空比为33%
	IEN2 |= 0x08; //允许REM中断	
	
	
}
															
void REM_Test(void)
{
	k = 0;
	rem_init();	
	switch(KEY)
	{
		case 1: 
			lcd_on();
			REM_num();
			ADD = ON_R;		
			break;
		case 0: 
			lcd_off();
			ADD = OFF_R; 
			break;
		default:
			break;				
	}
	REM_high();	
}

void REM_num(void)
{
	switch(TEMP)
	{
		case 17:
			ON_R[4] = 0x08;
			ON_R[5] = 0xF7;
		break;		
		case 18:
			ON_R[4] = 0x18;
			ON_R[5] = 0xE7;
		break;		
		case 19:
			ON_R[4] = 0x38;
			ON_R[5] = 0xC7;
		break;		
		case 20:
			ON_R[4] = 0x28;
			ON_R[5] = 0xD7;
		break;		
		case 21:
			ON_R[4] = 0x68;
			ON_R[5] = 0x97;
		break;		
		case 22:
			ON_R[4] = 0x78;
			ON_R[5] = 0x87;
		break;		
		case 23:
			ON_R[4] = 0x58;
			ON_R[5] = 0xA7;
		break;	
		case 24:
			ON_R[4] = 0x48;
			ON_R[5] = 0xB7;
		break;	
		case 25:
			ON_R[4] = 0xC8;
			ON_R[5] = 0x37;
		break;		
		case 26:
			ON_R[4] = 0xD8;
			ON_R[5] = 0x27;
		break;		
		case 27:
			ON_R[4] = 0x98;
			ON_R[5] = 0x67;
		break;		
		case 28:
			ON_R[4] = 0x88;
			ON_R[5] = 0x77;
		break;		
		case 29:
			ON_R[4] = 0xA8;
			ON_R[5] = 0x57;
		break;		
		case 30:		
			ON_R[4] = 0xB8;
			ON_R[5] = 0x47;
		break;	
		default:
			break;	
	}
}


void REM_high(void)
{
	bz = i = j = 0;
	if(k > 1)
	{ //发送完毕
		k = 0;
		PWM0CON &= 0x7F;			
		IDLE_FLG = 1;
	}
	else
	{
		PWM0CON |= 0x80; //PWM输出
		IEN2 &= 0xFE; //禁止外部中断使能
		REMNUMH = 0x80; //设置包络A中的38kHz载波个数，高包络标志
		REMNUML = 0xAB;	
	}
	
		
}

void REM_def(void)
{
	
	if(i == 5 && j == 8)
	{
		bz = 44;
		return;
	}
	if(ADD[i] & (0x80 >> j))
	{
		bz = 11;
		j++;
	}
	else
	{
		bz = 22;
		j++		;
	}
	if(j==8 && i< 5)
	{
		j = 0;
		i++;
	}
	
}


void REM_IntSetInfrared(void) interrupt 15
{
	
	
	switch(bz)
	{
		case 0: //引导码
			REMNUMH = 0x00; //4.5ms
			REMNUML = 0xAB;
			bz = 1;
			break;
		case 1: //脉冲
			REMNUMH = 0x80; //0.56ms
			REMNUML = 0x16;	
			REM_def();
			break;
		case 11: //1
			REMNUMH = 0x00; //1.685ms
			REMNUML = 0x40;	
		  bz = 1;
			break;
		case 22: //0
			REMNUMH = 0x00; //0.56ms
			REMNUML = 0x16;	
		  bz = 1;
			break;
		case 33: //重复
			k++;
		  REM_high();
			break;
		case 44: //尾部电平
		  REMNUMH = 0x00; //5.21ms
			REMNUML = 0xC5;	
			bz = 33;
			break;
		default:
			break;				
	}
	

}

																