部分单片机源码:
#define uchar unsigned char#define uint unsigned int
void delay(uint x) //延时函数
{
uint i,j;
for(i=x;i>0;i--)
for(j=0;j<110;j++); //执行110次约为1ms
}
void SystemInt() //系统初始化
{
TMOD = 0x51; //T0定时器 T1计数器 均采用方式1
TH0 = (65536-250)/256;
TL0 = (65536-250)%256; //定时250us
ET0 = 1; TR0 = 1; //打开T0
ET1 = 1;TR1 = 1; //打开T1
TH1 = 0;
TL1 = 0; //计数器初值为0
EA = 1; //开启总中断
IN1 = 1;
IN2 = 0; //初始正转
}
void PWMOUT() //PWM输出控制
{
if(cnt<PWMTime) //小于计数变量,输出高电平
{
PWM=1;
}
else
{
PWM=0; //大于计数变量,低电平
}
if(cnt>100)
cnt=0;
}
void SetSpeed() //速度设定
{
if(Add==0) //速度加
{
delay(100); //按键消抖
if(Add==0)
{
PWMTime+=10; //PWM波占空比增加10%
dw += 1; //档位加1
if(dw>9)
{
dw = 9;
}
while(Add==0); //松手检测
}
}
if(Sub==0) //如果速度减
{
delay(100); // 按键消抖
if(Sub==0)
{
PWMTime-=10; //PWM波占空比减少10%
dw -= 1; //档位减1
if(dw<0)
{
dw = 0;
}
while(Sub==0);
}
}
if(zhen==0) //正转
{
delay(100);
if(zhen==0)
{
IN1 = 1;
IN2 = 0;
while(zhen==0);
}
}
if(fan==0) //反转
{
delay(100);
if(fan==0)
{
IN1 = 0;
IN2 = 1;
while(fan==0);
}
}
if(Stop==0) //停止
{
delay(100);
if(Stop==0)
{
IN1 = 1;
IN2 = 1;
while(Stop==0);
}
}
}
void xianshi() //数码管显示速度和档位
{
uint shi,ge;
shi=speed/10;
ge=speed%10;
WE1 = 0;
P0 = table[ge]; //速度个位显示
delay(1);
WE1 = 1;
WE2 = 0;
P0 = table[shi]; //速度十位显示
delay(1);
WE2 = 1;
WE3 = 1;
WE4 = 0;
P0 = table[dw]; //档位显示
delay(1);
WE4 = 1;
}
void timer0() interrupt 1 //定时器
{
TH0 = (65536-250)/256;
TL0 = (65536-250)%256; //250us一次脉冲
cnt++;
time++;
if(time==4000) //1s时间内T1的脉冲次数 1除以250us
{
time = 0; //计数置0
TR0 = 0;TR1 = 0; //先关闭定时器
speed = TH1;
speed = speed << 8; //左移8位
speed += TL1; //赋值
speed = speed*2.2; //电机转一圈产生24个脉冲,转速为speed/24*60 r/min
TH1 = 0;TL1 = 0; //清0重新计数
TR0 = 1;TR1 = 1; //重新启动定时器
}
}
|