JDY-31与51单片机连接程序
时间: 2023-10-22 22:06:50 浏览: 76
以下是JDY-31模块与51单片机连接的示例程序,你需要根据你的具体应用进行修改:
```c
#include<reg52.h>
sbit LED=P0^1;
sbit TXD=P3^1;
sbit RXD=P3^0;
void Delay10ms(unsigned char c);
void InitUART();
void SendUART(unsigned char dat);
void main()
{
unsigned char i;
unsigned char uartdata;
InitUART();
while(1)
{
if(RI) // 判断串口是否接收到数据
{
RI=0;
uartdata=SBUF; // 读取接收到的数据
if(uartdata==0x31) // 如果接收到的数据为0x31
{
LED=1; // 点亮LED
for(i=0;i<3;i++) // 发送数据3次
{
SendUART(uartdata);
Delay10ms(1);
}
}
else if(uartdata==0x30) // 如果接收到的数据为0x30
{
LED=0; // 熄灭LED
for(i=0;i<3;i++) // 发送数据3次
{
SendUART(uartdata);
Delay10ms(1);
}
}
}
}
}
void InitUART()
{
TMOD=0x20; // 设置定时器1为模式2
TH1=0xfd; // 波特率设为9600
TL1=0xfd;
SCON=0x50; // 设置串口为模式1
TR1=1; // 启动定时器1
}
void SendUART(unsigned char dat)
{
SBUF=dat; // 发送数据
while(TI==0); // 等待发送完毕
TI=0; // 清除发送完成标志位
}
void Delay10ms(unsigned char c)
{
unsigned char i,j;
while(c--)
{
i=2;
j=239;
do
{
while(--j);
}while(--i);
}
}
```
在上面的程序中,我们先定义了JDY-31模块的TXD和RXD引脚分别连接到51单片机的P3.1和P3.0引脚上,LED连接到P0.1引脚上。
在主函数中,我们通过调用InitUART()函数初始化串口,并在while循环中不断判断是否接收到数据。如果接收到的数据为0x31,就点亮LED并发送3次0x31数据;如果接收到的数据为0x30,就熄灭LED并发送3次0x30数据。
InitUART()函数中,我们设置了定时器1为模式2,波特率为9600,串口为模式1,并启动定时器1。
SendUART()函数中,我们向串口发送一个字节的数据,并等待发送完成。
Delay10ms()函数实现了一个10毫秒的延时,用于等待数据发送完成。
相关推荐
![](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)