//---------------------------------------------
// NEC红外协议解码模块
//---------------------------------------------
#include "Infrared_nec_decode.h"
/*红外接收端口根据开发板重新设置*/
/*红外端口根据开发板重新设置*/
sbit INFRARED_RECV = P3^2;//红外接收头数据口连接的位置
//---------------------------------------------
//红外接收初始化
//设置定时器0工作方式1 16位定时器
//---------------------------------------------
void infrared_nec_decode_init()
{
TMOD &= 0x0f;
TMOD |= 0x10;
IT1 = 1;
EX1 = 1;
EA = 1;
}
//---------------------------------------------
// 获取高、低电平的计数值
// level为0时获取低电平,1时获取高电平
//---------------------------------------------
unsigned int infrared_nec_get_count(unsigned level)
{
TH1 = 0;
TL1 = 0;
TR1 = 1;
if(level)
while(INFRARED_RECV);
else
while(!INFRARED_RECV);
TR1 = 0;
return (TH1 * 256 + TL1);
}
//---------------------------------------------
// 解码NEC协议,将四字节解码结果存入缓冲区
// 返回值:0成功,1失败
//---------------------------------------------
unsigned char infrared_nec_get_code(unsigned char* buf)
{
unsigned int count = 0; //定时器计数
unsigned char i, j;
//计算是否为引导码
count = infrared_nec_get_count(0); //引导脉冲低电平8500~9500us
if(count < 7372 || count > 9216)
return 1;
count = infrared_nec_get_count(1); //引导脉冲高电平4000~5000us if(count < 3686 || count > 4608)
return 1;
for(i = 0; i < 4; i++) //4个字节
{
for(j = 0; j < 8; j++) //每个字节8位
{
count = infrared_nec_get_count(0); //200~800us
if(count < 184 || count > 737)
return 1;
count = infrared_nec_get_count(1); //200~2000us
if(count < 184 || count > 1843)
return 1;
buf[i] >>= 1;
if(count > 1032)
buf[i] |= 0x80;
}
}
return 0;
}