我用定时器定时0.01ms来输出PWM信号(周期1ms)来控制电机转速,并把占空比显示在数码管上,但是数码管怎么总是闪烁呢?是不是定时器中断函数拖了时间呢?
求程序优化
代码如下:
#include<reg52.h>
#include"main.h"
#include"delay.h"
void gostraight();
void turnleft();
void turnright();
void goback();
void inittimer0();
void PWM1speed();
void PWM2speed();
void display(uchar tmp1,uchar tmp2);
sbit PWM1=P3^0;
sbit PWM2=P3^1;
sbit RIN4=P3^2;
sbit RIN3=P3^3;
sbit LIN2=P3^4;
sbit LIN1=P3^5;
sbit P2_0 = P2^0;
sbit P2_1 = P2^1;
sbit P2_2 = P2^2;
sbit P2_3 = P2^3;
sbit s1=P2^4;
sbit s2=P2^5;
sbit s3=P2^6;
sbit s4=P2^7;
uchar code a[10]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};//共阳极0~9显示码
static int time=0;
uchar high1=50;
uchar high2=50;
uchar total=100;
void gostraight()
{
RIN3=0;
RIN4=1;
LIN1=0;
LIN2=1;
}
void turnleft()
{
RIN3=0;
RIN4=1;
LIN1=1;
LIN2=0;
}
void turnright()
{
RIN3=1;
RIN4=0;
LIN1=0;
LIN2=1;
}
void goback()
{
RIN3=1;
RIN4=0;
LIN1=1;
LIN2=0;
}
void inittimer0() //初始化T0
{
TMOD=0x01;
TH0=(65536-10)/256;
TL0=(65536-10)%256;
EA=1;
ET0=1;
TR0=1;
}
void PWM1speed() // 电机1占空比调节
{
if(s1==0)
{
delay_ms(5);
if(s1==0)
{
high1++;
if(high1==99)
{high1=1;}
}
}
if(s2==0)
{
delay_ms(5);
if(s2==0)
{
high1--;
if(high1==1)
{high1=total-1;}
}
}
// return (high1);
}
void PWM2speed() //电机2占空比调节
{
if(s3==0)
{
delay_ms(5);
if(s3==0)
{
high2++;
if(high2==99)
{high2=1;}
}
}
if(s4==0)
{
delay_ms(5);
if(s4==0)
{
high2--;
if(high2==1)
{high2=total-1;}
}
}
// return (high2);
}
void timer0() interrupt 1 //定时器中断
{
TH0=(65536-10)/256;
TL0=(65536-10)%256;
time++;
if(time<=high1)
{
PWM1=1;
}
else
{
PWM1=0;
}
if(time<=high2)
{
PWM2=1;
}
else
{
PWM2=0;
}
if(time>=total)
{time=0;}
}
void display(uchar tmp1,uchar tmp2) //显示占空比
{
uchar dat;
dat=tmp1/10;
P0=a[dat];
P2_0=1;
delay_ms(1);
P2_0=0;
dat=tmp1%10;
P0=a[dat];
P2_1=1;
delay_ms(1);
P2_1=0;
dat=tmp2/10;
P0=a[dat];
P2_2=1;
delay_ms(1);
P2_2=0;
dat=tmp2%10;
P0=a[dat];
P2_3=1;
delay_ms(1);
P2_3=0;
}
void main()
{
// uchar i;
// uchar j;
P0=0xff;
P2=0xFF;
inittimer0();
while(1)
{
PWM1speed();
PWM2speed();
display(high1,high2);
gostraight();
// turnleft();
// turnright();
// goback();
}
}
[
本帖最后由 chenjin59324 于 2013-3-5 21:22 编辑 ]
此帖出自
小平头技术问答
一周热门 更多>