#include"reg51.h"
#define uchar unsigned char
#define uint unsigned int
sbit duan=P2^0;
sbit wei=P2^1;
sbit mc=P3^2; //外部脉冲
sbit pmw1=P2^2; //EA
sbit pmw2=P2^3; //IN1
sbit pmw3=P2^4; //IN2
sbit Speed_high=P1^0; //加速
sbit Speed_low=P1^1; //减速
sbit Fan_turn=P1^2; //反转
uint count,num,num1,num3=50;
uint bai,shi,ge,zs;
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x27,0x7f,0x6f,0x40,0x7c,0x39,0x5e,0x79,0x71};//段码
uchar code weima[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};//位码
void Init_time();
void T0_time();
void T1_time();
void INT0_jishu();
void delay(uint jishi);//计时,以毫秒为单位
void display(uint bai,uint shi,uint ge);//显示转速
void main()
{
Init_time();
while(1)
{
display(bai,shi,ge);//显示电机速度
if(Speed_high==0) //检测加速按钮
{
delay(5);
if(Speed_high==0)
{
if(num3 >= 100)
num3 = 100;
else
num3=num3+10;
while(!Speed_high);//连续按键加速
}
}
if(Speed_low==0) //检测减速按钮
{
delay(5);
if(Speed_low==0)
{
if(num3 < 10)
num3 = 0;
else
num3=num3-10;
while(!Speed_low);//连续按键检测
}
}
if(Fan_turn==0) //检测加速按钮
{
delay(5);
if(Fan_turn==0)
{
pmw2=!pmw2;
pmw3=!pmw3;
while(!Fan_turn);//连续按键加速
}
}
}
}
//初始化设置
void Init_time()
{
TMOD=0x11;
pmw2=0;
pmw3=1;
TH1=(65536-50000)/256;
TL1=(65536-50000)%256; //每50ms计数
TH0=(65536-100)/256;
TL0=(65536-100)%256; //定时间隔为0.1ms,PWM
ET0=1;
TR0=1; //开定时器0
ET1=1;
TR1=1; //开定时器1
EX0=1; //外部中断允许
IT0=1; //设置下降触发中断
EA=1; //全局中断允许
}
//定时器0设置产生pwm波
void T0_time()interrupt 1 //计时0中断,每0.1毫秒一次
{
TR0=0;
TH0=(65536-100)/256;
TL0=(65536-100)%256;
num1++;
if(num1>=100)//PWM波完整周期为10ms
{
num1=0;
}
if(num1<=num3)//设置占空比
{
pmw1=1;
}
else
{
pmw1=0;
}
//pmw2=0;
TR0=1;
}
//定时器计数50ms,采集速度
void T1_time()interrupt 3
{
TR1=0;
TH1=(65536-50000)/256;
TL1=(65536-50000)%256;
num++;
if(num==20) //每1秒测速一次
{
num=0;
EX0=0; //关外部中断
zs=60*count/24; //求出速度
bai=zs/100;
shi=zs%100/10;
ge=zs%10;
count=0; //脉冲计数归零
EX0=1;
}
TR1=1;
}
//外部中断函数
void INT0_jishu() interrupt 0 using 1 //外部脉冲计数
{
count++ ;
}
//延时函数
void delay(uint jishi)
{
uint i,j;
for(i=jishi;i>0;i--)
for(j=110;j>0;j--);
}
//数码管显示函数
void display(uint bai,uint shi,uint ge)
{
duan=0;
wei=0;
duan=1; //百位显示
P0=table[bai];
duan=0;
delay(1);
P0=0x0;
wei=1;
P0=weima[5];
wei=0;
delay(1);
P0=0x0;
duan=1; //十位显示
P0=table[shi];
duan=0;
delay(1);
P0=0x0;
wei=1;
P0=weima[6];
wei=0;
delay(1);
P0=0x0;
duan=1; //个位显示
P0=table[ge];
duan=0;
delay(1);
P0=0x0;
wei=1;
P0=weima[7];
wei=0;
delay(1);
P0=0x0;
} |