|
发表于 2011-12-27 10:46:00
|
显示全部楼层
#include <reg52.h>
#include <string.h>
unsigned char g_ucRecBuff[20] = {0};
unsigned int g_iRecNum=0;
bit bReadOver=0;
//sbit Speak =P1^2;
//向串口发送一个字符
void SendChar(unsigned char ch)
{
SBUF=ch;
while(TI==0);
TI=0;
}
//向串口发送一个字符串,strlen为该字符串长度
void SerialSend(unsigned char *str,unsigned int strlen)
{
unsigned int k=0;
do
{
SendChar(*(str + k));
k++;
} while(k < strlen);
}
/********************************************************************
* 名称 : Com_Int()
* 功能 : 串口中断子函数
* 输入 : 无
* 输出 : 无
***********************************************************************/
void Serial_Int(void) interrupt 4 using 3
{
ES = 0;
if(RI == 1) //当硬件接收到一个数据时,RI会置位
{
g_ucRecBuff[g_iRecNum] = SBUF; //把从串口读出的数存到数组
RI = 0;
g_iRecNum++;
if(g_iRecNum == 20)
{
g_iRecNum = 0; //当com_dat = 21时,清0,防止数组溢出
bReadOver = 1;
}
}
ES = 1;
}
/********************************************************************
* 名称 : Com_Init()
* 功能 : 串口初始化,晶振11.0592,波特率9600,使能了串口中断
* 输入 : 无
* 输出 : 无
***********************************************************************/
void SerialInit(void)
{
TMOD = 0x20; //定时器工作在定时器1的方式2
PCON = 0x00; //不倍频
SCON = 0x50; //串口工作在方式1,并且启动串行接收
TH1 = 0xFd; //设置波特率 9600
TL1 = 0xFd;
TR1 = 1; //启动定时器1
ES = 1; //开串口中断
//EA = 1; //开总中断
g_iRecNum=0;
memset(g_ucRecBuff,0xff,sizeof(g_ucRecBuff));
bReadOver=0;
}
//返回接收到的字符
unsigned int GetRecDate(unsigned char *pucRec)
{
if(bReadOver)
{
memcpy(pucRec,g_ucRecBuff,20);
memset(g_ucRecBuff,0,sizeof(g_ucRecBuff));
bReadOver=0;
g_iRecNum=0;
return 1;
}
return 0;
} |
|