帮我用stc15w408as单片机写一个红外模块,当按下遥控器任意按键,向串口发送数据的代码
时间: 2024-01-24 17:17:13 浏览: 33
好的,下面是基于STC15W408AS单片机的红外模块代码:
```
#include <STC15W4K48S4.H>
#define FOSC 24000000UL // 时钟频率
#define BAUD 9600 // 串口波特率
sbit IR_IN = P3^2; // 接收红外信号的引脚
sbit IR_OUT = P3^3; // 发送红外信号的引脚
unsigned char irCode[4]; // 存储红外信号的数组
unsigned char irCount = 0; // 红外信号接收计数器
void InitUART() // 初始化串口
{
SCON = 0x50; // 8位数据,可变波特率
TMOD &= 0x0F; // 设置定时器1为16位自动重载模式
TMOD |= 0x20;
TH1 = TL1 = -(FOSC/12/32/BAUD); // 定时器1初值
TR1 = 1; // 启动定时器1
ES = 1; // 使能串口中断
EA = 1; // 使能总中断
}
void InitTimer() // 初始化定时器
{
TMOD &= 0xF0; // 设置定时器0为模式1(16位定时器)
TMOD |= 0x01;
TH0 = 0xFC; // 定时器初值,定时50us
TL0 = 0x18;
ET0 = 1; // 使能定时器0中断
TR0 = 1; // 启动定时器0
}
void SendByte(unsigned char dat) // 发送一个字节
{
SBUF = dat;
while(!TI); // 等待发送完成
TI = 0; // 清除发送完成标志位
}
void SendData(unsigned char *buf, unsigned char len) // 发送数据
{
unsigned char i;
for(i=0; i<len; i++)
{
SendByte(buf[i]);
}
}
void IRIntrHandler() interrupt 0 // 外部中断0,红外信号接收
{
static unsigned int lastTime = 0; // 上一次中断时间
unsigned int thisTime = TH0*256 + TL0; // 本次中断时间
unsigned int pulseWidth = thisTime - lastTime; // 脉冲宽度
lastTime = thisTime; // 更新上一次中断时间
if(pulseWidth > 10000) // 空闲时间超过10ms,表示一组信号的开始
{
irCount = 0; // 重置计数器
}
else if(pulseWidth > 4000 && pulseWidth < 5000) // 560us的脉冲表示逻辑0
{
irCode[irCount/8] &= ~(1<<(7-irCount%8)); // 存储到数组中
irCount++; // 计数器加1
}
else if(pulseWidth > 8000 && pulseWidth < 9000) // 1.7ms的脉冲表示逻辑1
{
irCode[irCount/8] |= 1<<(7-irCount%8); // 存储到数组中
irCount++; // 计数器加1
}
else if(pulseWidth > 2000 && pulseWidth < 3000) // 450us的脉冲表示一组信号的结束
{
if(irCount == 32) // 接收到完整的红外信号
{
SendData(irCode, 4); // 发送红外信号到串口
}
irCount = 0; // 重置计数器
}
}
void main()
{
InitUART(); // 初始化串口
InitTimer(); // 初始化定时器
while(1);
}
void Timer0IntrHandler() interrupt 1 // 定时器0溢出中断
{
TH0 = 0xFC; // 定时50us
TL0 = 0x18;
IR_OUT = ~IR_OUT; // 发送红外信号
}
```
在上述代码中,`IR_IN`和`IR_OUT`分别代表接收和发送红外信号的引脚。当接收到完整的红外信号后,会通过串口发送到计算机。你可以通过串口调试助手等工具来接收和解析这些数据。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)