这个程序用的
单片机是STC12C5A60S2,双串口
通信。但是偶尔会有出现乱码,看看是不是程序有问题?谢谢了!
#include<STC12C5A.h>
#include<string.h>
unsigned char flag1,flag2,temp1,temp2,num,num1;
unsigned char temp[50]={0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,};
void delay(unsigned int i);
#define S2RI 0x01 //串口2接收中断请求标志位
#define S2
ti 0x02 //串口2发送中断请求标志位
sbit OUT=P1^6;
/****************串行口初始化函数****************/
void InitUART(void)
{
TMOD = 0x20; //定时器1工作在方式2 8位自动重装
SCON = 0x50; //串口1工作在方式1 10位异步收发 REN=1允许接收
PCON = 0x80;
TH1 = 0xFD; //定时器1初值
TL1 = TH1;
TR1 = 1; //定时器1开始计数
EA =1; //开总中断
ES =1; //开串口1中断
S2CON = 0x50; //串口2工作在方式1 10位异步收发 S2REN=1允许接收
BRT = 0xFD; //独立波特率发生器初值
AUXR = 0x18; //BRTR=1 独立波特率发生器开始计数
IE2 =0x01; //开串口2中断 ES2=1
}
/****************串行口1发送****************/
void UART_1SendOneByte(unsigned char c)
{
SBUF = c;
while(!TI); //若TI=0,在此等待
TI = 0;
}
/****************串行口2发送****************/
void UART_2SendOneByte(unsigned char c)
{
S2BUF = c;
while(!(S2CON&S2TI)); //若S2TI=0,在此等待
S2CON&=~S2TI; //S2TI=0
}
/*****************主函数******************/
void main(void)
{
EX1=1; //外部中断1开
IT1=1; //IT1=1表示边沿触发
InitUART(); //串行口初始化
OUT=1;
while(1)
{
//如果串口1接收到数据,将此数据由串口2发送
flag1=0;
if(num>=1&&flag1==0)
{
delay(10);
if(num>=1&&flag1==0)
{
EA=0;
for(num1=0;num1<num;num1++)
{
temp1=temp[num1];
UART_2SendOneByte(temp1);
}
num=0;
EA=1;
}
}
if(temp2==6&&flag2==1)
{
EA=0;
flag2=0;
if(num1<5)UART_1SendOneByte(temp2);
OUT=0;
temp2=0;
IE1=0;
EX1=1;
EA=1;
}
if(temp2==21&&flag2==1)
{
EA=0;
OUT=1;
flag2=0;
UART_1SendOneByte(temp2);
temp2=0;
EA=1;
}
}
}
/************INT1中断**************/
void ISR_INT1(void) interrupt 2
{
EX1=0;
OUT=1;
temp2=6;
UART_1SendOneByte(temp2);
temp2=0;
IE1=0;
}
/************串行口1中断处理函数*************/
void UART_1Interrupt(void) interrupt 4
{
if(RI==1)
{
RI=0;
temp[num]=SBUF;
num=num+1;
if(num==50)num=49;
flag1=1;
}
}
/************串行口2中断处理函数*************/
void UART_2Interrupt(void) interrupt 8
{
if(S2CON&S2RI)
{
S2CON&=~S2RI;
temp2=S2BUF;
flag2=1;
}
}
void delay(unsigned int i)
{
unsigned char j;
for(i; i > 0; i--)
for(j = 200; j > 0; j--) ;
}
一周热门 更多>