/*****************************************************************************************
uart.c
模块功能:串口设备驱动模块
使用示例:通过串口接收数据,然后将接收到的数据直接放回。
#include "uart.h"
...
{
char buf[10];
UartInit(B115200);
if(UartReceive(buf))
{
...
UartSend(buf,sizeof(buf));
}
}
版本说明:V1.0
*****************************************************************************************/
#include <reg51.h>
#include "uart.h"
#include "timer.h"
static unsigned char UartBufSend[MAXLEN],UartBufReceive[MAXLEN]; //发送长度数组,接收长度数组
static unsigned char ReceiveLen = 0x00,SendLen = 0x00,SendOK = 0x00;//接收长度,发送长度,当前发送多少字符
void UartInit(unsigned char baundrate);
void UartSend(unsigned char *ptr,unsigned char len);
int UartReceive(unsigned char *ptr);
/***************************************************************************************
函数名称:UartInit
函数功能:使用指定的波特率初始化串口
形 参: baundrate / 波特率
返 回 值:无
****************************************************************************************/
void UartInit(unsigned char baundrate)
{
ES = 0;
TMOD = (TMOD & 0x0F) | 0x20;//选定时器T1,设置工作方式为2
SCON = 0x50;//设定串口工作方式是1
PCON = 0x80;//SMOD为1
switch (baundrate)
{
case B9600:
break;
case B19200:
break;
case B38400:
break;
case B57600:
break;
case B115200:
TH1 = 0xFF;
TL1 = 0xFF;
break;
default:
break;
}//选定波特率设置初值
TR1 = 1;//开始计时
ES = 1;
EA = 1;
}
/***************************************************************************************
函数名称:UartSend
函数功能:将指定位置处指定长度的数据通过串口发送
形 参:ptr / 发送数据首地址 len 发送数据长度
返 回 值:无
****************************************************************************************/
void UartSend(unsigned char *ptr,unsigned char len)
{
unsigned char i;
while (SendLen); //等待串口数据发送结束
for (i = 0;i < len ;i++ )
{
*(UartBufSend + i) = *(ptr + i);
}//发送数据
SendLen = len;//发送数据的长度
SendOK = 0x00;//以发送的数据
TI=1;//模拟中断
}
/***************************************************************************************
函数名称:UartReceive
函数功能:通过串口接收数据,接收的数据存放在ptr处
形 参:ptr/存放首地址
返 回 值:接收数据长度
***************************************************************************************/
int UartReceive(unsigned char *ptr)
{
char i;
if (ReceiveLen && Timer1 > 10)//已有多长时间未接受数据就可断定数据接收完了
{
for (i=0;i<ReceiveLen;i++)
{
*(ptr + i) = *(UartBufReceive + i);
}//接收数据
i = ReceiveLen;//接收数据的长度
ReceiveLen = 0x00;//清零
return i;//返回接收数据的长度
}
else
{
return 0;
}
}
/***************************************************************************************
函数名称:UartInter
函数功能:串口中断服务函数
形 参:无
返 回 值:无
***************************************************************************************/
void UartInter(void) interrupt 4
{
if (TI)
{
TI = 0;
if (SendLen)
{
SBUF = UartBufSend[SendOK];//发送数据
++SendOK;//以发送完的数据长度增加
--SendLen;//发送的长度计数减1
}
}
else
{
RI = 0;
Timer1 = 0x00;//发送一个数据定时器就清零
if (ReceiveLen < sizeof(UartBufReceive))
{
UartBufReceive[ReceiveLen] = SBUF;//接收数据
++ReceiveLen;//接收的数据长度加1
}
else
{
ReceiveLen = 0;//发送长度为0
}
}
}
/*********************************End***************************************************/