#include <AT89X52.h>
#include "uart.h"
#define uint unsigned int
#define uchar unsigned char
extern void beep(void);
sbit IR = P3^2;//红外端口
uchar num;
unsigned char ir_value = 255;
uchar key_code = 0;//遥控键值
uchar new_code = 0;//有无新按键
uint buf_key_code=0;//键值暂存
uchar key_bit_count=0;//键编码脉冲计数
uint count=0;//定时中断次数计数
uint buf_count=0;//定时中断计数暂存
uchar common_code_count=0;//前导码脉冲计数
uchar ir_status=0;//脉冲接收器所处的状态,0:无信号,1:系统码接收区,2:数据编码接收区
//bit ir_flag;
unsigned char ir_a[2];
void delay_10us(unsigned char y)///延时子程序10us
{
unsigned char x;
for(x = y;x>0;x--);
}
void delay_ms(uint z)//延时子程序1ms
{
uint x,y;
for(x=z;x>0;x--)
for(y=113;y>0;y--);
}
void ir_ctr_init(void)/////初始化
{
IR = 1; //红外端口写1
EA = 1; //开总中断
TMOD = 0x02; //定时器0,模式2,8位自动装载模式
TH0 = 0Xd1; //定时50us
TL0 = 0Xd1;
IT0 = 1; //INT1下降沿触发
ET0 = 1; //允许定时器中断
EX0 = 1; //允许外部中断
}
/***********************************************
定时器中断
***********************************************/
void time0() interrupt 1///定时器中断
{
count++;//定时器中断次数累加
}
/**********************************************
外部中断,红外解码程序
**********************************************/
void int0() interrupt 0///外部中断
{
TR0 = 1;//开定时器中断
if((count > 12)&&(count < 270))//如果信号合法,则放入buf_count,count清0,对下一个脉冲信号计时
{
buf_count = count;
count = 0;
}
delay_10us(10);//延时100us以消除下降沿跳变抖动
if(IR == 0)//INT1引脚稳定为低电平,则无法确实是信号,count重新计时,因上面延时了50us,故要补偿1次TO中断
{
count = 2;
}
if(buf_count > 12&&buf_count < 270)//若收到的信号合法,则再进行信号分析
{
if(ir_status == 0)//如果之前未收到引导码
{
if(buf_count > 210&&buf_count < 270)//判断是否引导码13.5ms
{
ir_status = 1;//系统标记
buf_count = 0;//
}
}
else if(ir_status == 1)///收到引导码
{
if(common_code_count >= 15)//若收完16个脉冲
{
ir_status = 2;//数据解码标记
common_code_count = 0;//系统码计算清零
buf_count = 0;//中断计数暂存清0
}
else if((buf_count > 40&&buf_count < 70)||(buf_count > 12&&buf_count < 32))
{
buf_count = 0;
common_code_count++;//每收到一个信号自加1
}
}
else if(ir_status == 2)//进入数据编码接收
{
if(key_bit_count < 16)//收到数据少于16位,则将收到的数据写入buf_key_code
{
if(buf_count>40&&buf_count<70)
{
buf_count=0;
buf_key_code >>= 1;
buf_key_code |= 0x80;//收到1
key_bit_count++;//数据脉冲累加
}
else if(buf_count > 12&&buf_count < 32)//收到0
{
buf_count=0;
buf_key_code >>= 1;//收到0
key_bit_count++;
}
if(key_bit_count == 8)
{
ir_a[0] = buf_key_code;
}else if(key_bit_count == 16)
{
ir_a[1] = buf_key_code;
}
}
else //若收完8位数据则做以下处理
{
ir_status = 0;//接收状态返回到空闲
key_bit_count = 0;
buf_key_code = 0;
buf_count = 0;
TR0 = 0;
new_code = 1;
if(ir_a[0] == ~ir_a[1])
{
ir_value = ir_a[0];
//trans(ir_value);
}
}
}
}
}
unsigned char ir_char_read(void)
{
unsigned char ir_temp;
ir_temp = ir_value;
ir_value = 255;
return (ir_temp);
}