在用STC_60s2单片机进行双串口同时收发时,要注意一些容易配置错误的地方。AUXR寄存器有很多功能。在对其中的位置位和复位时,很可能在不同的地方多次进行,应该使用AUXR |= bitx 和AUXR &=~bitx 语句进行对某一位的置位和复位。这样就不会影响其他功能位了。
附上程序:
#include
//sfr AUXR = 0x8E;
#define uchar unsigned char//
#define uint unsigned int //
#define BUADRATE 38400
#define FOSC 24000000
#define S2RI 0x01
#define S2TI 0x02
sbit LED1 = P2^7;
uchar ReceBuf[200]={0};
bit finishflag = 0;
uchar revcnt = 0;
uchar startflag = 0;
void InitUART1(void) //baudrate 115200
{
TMOD = 0x20;
SCON = 0x50;
TH1 = 0xf3; //115384
TL1 = TH1;
PCON = 0x80; //SMOD = 1;
ES = 1;
TR1 = 1;
}
void InitUART2() //baudrate 38400
{
S2CON = 0x50; //8-Bit 串口模式 允许接收
BRT = 236; //[24000000/(256-236)]/32 = 37500 error2.34%
AUXR |= 0x14; //BRTR=1使能BRT BRTx12=1 不分频 (AUXR 第二次出现,不能用‘=’应该用“|=”)
IE2 = 0x01; //enable UART2 interrupt
AUXR1 = 0; //UART2 TXD->P1.3 RXD->P1.2
}
void SendOneByte(unsigned char c)
{
SBUF = c;
while(!TI);
TI = 0;
}
void U1SendString(uchar *dat)
{
while(*(dat)!='\0')
{
SendOneByte(*dat);
dat ;
}
}
void U2SendOneByte(unsigned char c)
{
S2BUF = c;
while(!(S2CON & S2TI));
S2CON &= ~S2TI;
}
void U2SendString(uchar *dat)
{
while(*(dat)!='\0')
{
U2SendOneByte(*dat);
dat ;
}
}
void main()
{ uchar temp = 0x01;
AUXR = AUXR|0x40; // T1, 1T Mode AUXR 第一次出现
InitUART1();
EA = 1;
SendOneByte(0xaa);
SendOneByte(0xbb);
SendOneByte(0xcc);
InitUART2();
SendOneByte(0xdd);
while(1)
{// temp = ~temp;
// U2SendOneByte(temp);
if(finishflag)
{ LED1 = 1;
finishflag = 0;
U1SendString(ReceBuf);
LED1 = 0;
}
}
}
void UART1ISR(void) interrupt 4
{
if(RI)
{
RI = 0;
//add your code here!
}
else
TI = 0;
}
void UART2ISR(void) interrupt 8
{ static bit flash=0;
static uchar i=0;
static uchar endcnt = 0;
uchar tempdat = 0;
if(S2CON & S2RI)
{
S2CON &= ~S2RI;
if(~finishflag)
{
flash=~flash;
// LED1 = flash;
tempdat = S2BUF;
if(tempdat=='$')
{
startflag = 1;
}
////////////////////////////////////////////////////////////
if(startflag)
{
ReceBuf[i] = tempdat;
i ;
////////////////////////////////////////////////////////////
if(i==6&&ReceBuf[3]!='R'&&ReceBuf[5]!='C') //判断是不是$GPRMC帧
{
startflag = 0;
i = 0;
}
else if(ReceBuf[i-1]=='*')
{
endcnt ;
if(endcnt==2)
{
revcnt = i;
endcnt = 0;
i = 0;
finishflag = 1;
startflag = 0;
}
}
else ;
}
}
else ;
}
else
S2CON &= ~S2TI;
}