AT89C51 L298N 控制直流电机 PWM 等问题

2024-11-29 11:56:43
推荐回答(1个)
回答1:

#include
sbit P0_0=P0^0; /*开始、停止*/
sbit P0_1=P0^1; /*转向*/
sbit P0_2=P0^2; /*左转*/
sbit P0_3=P0^3; /*右转*/
sbit P0_4=P0^4; /*加速*/
sbit P0_5=P0^5; /*减速*/
sbit P2_0=P2^0;
sbit P2_1=P2^1;
sbit P2_2=P2^2;
sbit P2_3=P2^3;
sbit P2_4=P2^4;
sbit P2_5=P2^5;
unsigned char time=0;
unsigned char period=30;
unsigned char high=15;
unsigned char dir=0;

/*void delay(void)
{
unsigned char j;
for(j=0;j<124;j++);
}*/

void timer0() interrupt 1 using 1
{
TH0=0xFF; /*定时器初值重装载*/
TL0=0xAC;
time++;
if(dir%2==1)
{
if(time==high) /*高电平持续时间结束,变低*/
{
P2_0=0; /*经过反相器反相*/
P2_2=0;
}
else if(time==period) /*周期时间到,变高*/
{ time=0;
P2_0=1; /*经过反相器反相*/
P2_2=1;
}

}
else if(dir%2==0) /*高电平持续时间结束,变低*/
{
if(time==(period-high))
{
P2_1=1;
P2_3=1;
} /*经过反相器反相*/
else if(time==period) /*周期时间到,变高*/
{
time=0;
P2_1=0; /*经过反相器反相*/
P2_3=0;
}

}
}

void main()
{
unsigned char n=0;
unsigned char j=1;
unsigned char k=1;
P0=0x00;
P2_0=1;
P2_1=0;
P2_2=1;
P2_3=0;
P2_4=0;
P2_5=0;

TMOD=0x01; /*定时器0方式1*/
TH0=0xFF;
TL0=0xAC;

ET0=1; /*开定时器0中断*/
TR0=1; /*启动定时器0*/

while(1)
{
if(P0_0==1)
{
n++;
if(n%2==1)
{
EA=1; /*开CPU中断*/
P2_4=1;
P2_5=1;
}
else if(n%2==0)
{
EA=0; /*关CPU中断*/
P2_4=0;
P2_5=0;
}
while(P0_0!=0)
{};
}
if(P0_1==1)
{
dir++; /*转向控制*/
while(P0_1==1)
{};

}
if(P0_2==1)
{
j++;
if(j%2==1)
{P2_4=1;}
else if(j%2==0)
{P2_4=0;}
while(P0_2!=0)
{};
}
if(P0_3==1)
{
k++;
if(k%2==1)
{P2_5=1;}
else if(k%2==0)
{P2_5=0;}
while(P0_3!=0)
{};
}

if(P0_4==1)
{
high++;
if(high==30)
high=30;
while(P0_4!=0)
{};
}
if(P0_5==1)
{
high--;
if(high==0)
high=0;
while(P0_5!=0)
{};
}

}

}