微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 51 串口收发程序源代码 环形缓冲区实现

51 串口收发程序源代码 环形缓冲区实现

时间:12-02 来源:互联网 点击:
部分代码:

/***** 51 串口收发 环形缓冲区实现 *****
* 版本.........: 1.0
* 目标.........: STC12C5A32AD
* 文件名.......: uart.c

* 编译器.......: Keil C51 V9.02
**************************************/
#include "uart.h"
#include "uart_config.h"
#include "main_config.h"
#include "STC_NEW_8051.H"

volatileunsignedcharUART_TxBuf[UART_TXBUF_SIZE];
volatileunsignedcharUART_TxBuf_Index=0;
volatileunsignedcharUART_TxBuf_Length=0;

volatileunsignedcharUART_RxBuf[UART_RXBUF_SIZE];
volatileunsignedcharUART_RxBuf_Index=0;
volatileunsignedcharUART_RxBuf_Length=0;

volatilebitUART_RxBuf_IsFull=0;

voidUART_Init(void)
{
PCON&=0x7f;//波特率不倍速
SCON=0x50;//8位数据,可变波特率
AUXR|=0x40;//定时器1时钟为Fosc,即1T
AUXR&=0xfe;//串口1选择定时器1为波特率发生器
TMOD&=0x0f;//清除定时器1模式位
TMOD|=0x20;//设定定时器1为8位自动重装方式
TL1=256-(unsignedchar)(F_CPU/UART_BAUD/32+0.5);//设定定时初值
TH1=256-(unsignedchar)(F_CPU/UART_BAUD/32+0.5);//设定定时器重装值
ET1=0;//禁止定时器1中断
TR1=1;//启动定时器1

ES=1;
TI=0;

EA=1;// 使能总中断
}

volatileunsignedcharUART_Sending=0;

voidUART_TxByte(unsignedcharbyte)
{
EA=0;
if(UART_Sending)
{
EA=1;
while(UART_TxBuf_Length>=UART_TXBUF_SIZE);// 等待数据发送,不丢失
EA=0;
if(UART_TxBuf_Length{
UART_TxBuf[UART_TxBuf_Index]=byte;
UART_TxBuf_Length++;
UART_TxBuf_Index++;
if(UART_TxBuf_Index>=UART_TXBUF_SIZE)
UART_TxBuf_Index=0;
}
}
else
{
SBUF=byte;
UART_Sending=1;
}
EA=1;
}

unsignedchartemp=0;
voidUART_ISR(void)interrupt4
{
EA=0;
if(TI)
{
TI=0;
if(UART_TxBuf_Length==0)
{
UART_Sending=0;
}
else
{
if(UART_TxBuf_Index>=UART_TxBuf_Length)
SBUF=UART_TxBuf[UART_TxBuf_Index-UART_TxBuf_Length];
else
SBUF=UART_TxBuf[UART_TXBUF_SIZE+UART_TxBuf_Index-UART_TxBuf_Length];
UART_TxBuf_Length--;
}
}
if(RI)
{
RI=0;
temp=SBUF;
if(UART_RxBuf_Length{
UART_RxBuf[UART_RxBuf_Index]=temp;
UART_RxBuf_Length++;
UART_RxBuf_Index++;
if(UART_RxBuf_Index>=UART_RXBUF_SIZE)
UART_RxBuf_Index=0;
}
else
{
UART_RxBuf_IsFull=1;
}
}
EA=1;
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top