51单片机定时和串口冲突?

定时器T0产生PWM波,T1控制波特率串口通信。可是加上T0,串口就没有数据接收,T0正常产生波。把T0初始化函数去掉,串口就正常接收数据。用的是STC89C52。
void timer_init()
{
TMOD=0x21;
SCON=0X53;
TH1=0xfd;
TL1=0xfd;
ET1=1;
TR1=1;
TH0=0xFF;
TL0=0xF6;
ET0=1;
TR0=1;
ES=1;
EA=1;
}
void timer0_int() interrupt 1
{

TR0=0; //设置定时器初值期间,关闭定时器
TH0=0xFF;
TL0=0xF6;
TR0=1;

time++;
if(time<50) //count为占空比
{
PWM=1; //输出高电平
}
else
PWM=0;
if(time>=100)
{
time=0;
}
}
void ser() interrupt 4
{
if (RI)
{
RI=0;
Re_buf[counter]=SBUF;

if(counter==0&&Re_buf[0]!=0x55) return; //第0号数据不是帧头

counter++;
if(counter==11) //接收到11个数据
{
counter=0; //重新赋值,准备下一帧数据的接收
switch(Re_buf [1])
{
case 0x53:
ucStrAngle[0]=Re_buf[2];
ucStrAngle[1]=Re_buf[3];
ucStrAngle[2]=Re_buf[4];
ucStrAngle[3]=Re_buf[5];
ucStrAngle[4]=Re_buf[6];
ucStrAngle[5]=Re_buf[7];
break;
}
}
}
Vax = ((short)(ucStrAngle[1]<<8| ucStrAngle[0]))/32768.0*180;
if(Vax>0)
{
x=1;
xx=0;
}
else if(Vax<=0)
{
x=0;
xx=1;
}
}

程序需要做些修改,修改如下:

void timer_init()

TMOD=0x22;//最好用模式2,10个机器周期就中断,最好减少服务时间
SCON=0X50;
TH1=0xfd;
TL1=0xfd;
//ET1=1;这是不允许的
TR1=1;
TH0=0xF6;
TL0=0xF6;
ET0=1;
TR0=1;
ES=1;
EA=1; 

void timer0_int() interrupt 1 
{
time++;
if(time<50) //count为占空比
{
PWM=1; //输出高电平
}
else 
PWM=0;
if(time>=100)
{
time=0;
}
}
void ser() interrupt 4
{
if (RI)
{
RI=0;
Re_buf[counter]=SBUF;

if(counter==0&&Re_buf[0]!=0x55) return; //第0号数据不是帧头

counter++; 
if(counter==11) //接收到11个数据

counter=0; //重新赋值,准备下一帧数据的接收 
switch(Re_buf [1])
{
case 0x53: 
ucStrAngle[0]=Re_buf[2];
ucStrAngle[1]=Re_buf[3];
ucStrAngle[2]=Re_buf[4];
ucStrAngle[3]=Re_buf[5];
ucStrAngle[4]=Re_buf[6];
ucStrAngle[5]=Re_buf[7];
break;

}
}
Vax = ((short)(ucStrAngle[1]<<8| ucStrAngle[0]))/32768.0*180;
if(Vax>0)
{
x=1;
xx=0;
}
else if(Vax<=0)
{
x=0;
xx=1;
}
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答