一、代码实现
//初始化,采用定时器2生成波特率,使用isp生成,12MHz,串口1,12T
void UartInit() //9600bps@12.000MHz
{
SCON = 0x50; //8位数据,可变波特率
AUXR |= 0x01; //串口1选择定时器2为波特率发生器
AUXR &= 0xFB; //定时器2时钟为Fosc/12,即12T
T2L = 0xE6; //设定定时初值
T2H = 0xFF; //设定定时初值
AUXR |= 0x10; //启动定时器2
EA = 1;
ES = 1;
}
//发送单字节,采用查询方式
void Send_byte(unsigned char dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
//发送字符串
void Send_string(unsigned char *str)
{
while(*str != '\0')
{
Send_byte(*str++);
}
}
//接收数据,采用中断,数据可为字符串或存在数组中
void Receive() interrupt 4
{
if(RI == 1)
{
RI = 0;
redat[index] = SBUF;
index++;
}
}
二、试验样例
//试验现象:上电串口收到anb!,向串口发送kc,led全部点亮
#include "stc15f2k60s2.h"
#include "intrins.h"
unsigned char xdata redat[10] = {'n','b','!'};
unsigned char index = 0;
void UartInit() //9600bps@12.000MHz
{
SCON = 0x50; //8位数据,可变波特率
AUXR |= 0x01; //串口1选择定时器2为波特率发生器
AUXR &= 0xFB; //定时器2时钟为Fosc/12,即12T
T2L = 0xE6; //设定定时初值
T2H = 0xFF; //设定定时初值
AUXR |= 0x10; //启动定时器2
EA = 1;
ES = 1;
}
void Send_byte(unsigned char dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
void Send_string(unsigned char *str)
{
while(*str != '\0')
{
Send_byte(*str++);
}
}
void Receive() interrupt 4
{
if(RI == 1)
{
RI = 0;
redat[index] = SBUF;
index++;
}
}
void main()
{
UartInit();
P2 = (P2 & 0x1f) | 0x80;
P0 = 0xff;
Send_byte('a');
Send_string(redat);
while(1)
{
if((redat[0] == 'k') && (redat[1] == 'c'))
{
P2 = (P2 & 0x1f) | 0x80;
P0 = 0x00;
}
}
}
三、注意点
1.如果想向上位机发送数字的字符,可以在数字基础上加上'0'即变为对应字符。可参考第10届国赛串口功能。
a = distance_smg /10 + '0';
Send_byte(a);
2.反斜杠的字符表示是' \\ '
注:本笔记仅作个人学习使用。