///////
51单片机蓝牙测试代码
////////
#include <reg52.h>
typedef unsigned char u8;
typedef unsigned int u16;
u8 r_buf; //蓝牙接收到的字符存储缓冲区
sbit led1 = P1^0; //灯1,当接收字符0时,灯1亮
sbit led2 = P1^1; //灯2,当接收字符1时,灯2亮
sbit led3 = P1^2; //灯2,当接收其它字符时,灯3亮
sbit led4 = P1^3; //蓝牙连接状态灯,当蓝牙连通时,灯4亮
sbit state = P3^6; //蓝牙连通的状态标志位
void delay(u16 z) //延迟函数
{
u16 x,y;
for(x=z;x>0;x--)
for(y=125;y>0;y--);
}
void InitUART() //串口初始化9600
{
//初始化串口定时器9600
TMOD = 0x20;
PCON = 0x00;
SCON = 0x50;
TH1 = 0xFF;
TL1 = 0xFD;
TR1 = 1;
ES = 1;
EA = 1;
}
void SendOneByte(unsigned char c) //发送字符函数
{
SBUF = c;
while(!TI);
TI = 0;
}
void main(void)
{
InitUART();
led1 = 1;
led2 = 1;
led3 = 1;
led4 = 1;
r_buf = '2';
while(1)
{
if(state == 1)//蓝牙连通状态判断
{
led4 = 0; //如果蓝牙匹配成功,灯4亮
}
else
{
led4 = 1; //如果蓝牙匹配不成功,灯4不亮
}
}
}
void UARTInterrupt(void) interrupt 4 //串口接收字符
{
if(RI)
{
RI = 0;
//add your code here!
r_buf = SBUF;
if(r_buf == '0')//如果为字符‘0’,灯1亮
{
led1 = 0;
delay(1000);
led1 = 1;
}
if(r_buf == '1')//如果为字符‘1’,灯2亮
{
led2 = 0;
delay(1000);
led2 = 1;
}
else //如果为其它字符,灯3亮
{
led3 = 0;
delay(1000);
led3 = 1;
}
SendOneByte(r_buf);//回发该字符
}
} |