目的:两个按键控制两个直流电机调速,长按键(>=2s)时对应电机加速,相反减速。(补充:该程序在一个按键一个电机时达到要求,当程序中补充到两个电机两个按键时未达到要求,出现的问题是按键时间长短好像都是出现的减速,而且有时按好几下才减,在该程序下连接一个电机也是上述问题),望高手指点。
————自学51小菜鸟
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit U1=P1^1;
sbit U2=P1^2;
sbit KEY1=P3^4;
sbit KEY2=P3^3;
uchar num,num1,num2,keytime,keynum,numt,numspeed1,numspeed2;
void delayms(uint xms)
{
uint i,j;
for(i=xms;i>0;i--)
for(j=110;j>0;j--);
}
void keyscan()
{
if(KEY1==0||KEY2==0)
{
delayms(10);
if(KEY1==0||KEY2==0)
{
if(KEY1==0) keynum=1;
if(KEY2==0) keynum=2;
while((!KEY1)||(!KEY2))
{
TR1=1;
}
TR1=0;
keytime=numt;
numt=0;
}
if(keytime>=40)
{
switch(keynum)
{
case 1:
{
{
numspeed1=numspeed1+2;
if(numspeed1>16)
numspeed1=8;
}
keynum=0;
break;
}
case 2:
{
{
numspeed2=numspeed2+2;
if(numspeed2>16)
numspeed2=8;
}
keynum=0;
break;
}
}
}
if(keytime<40)
{
switch(keynum)
{
case 1:
{
{
numspeed1=numspeed1-2;
if(numspeed1<8)
numspeed1=8;
}
keynum=0;
break;
}
case 2:
{
{
numspeed2=numspeed2-2;
if(numspeed2<8)
numspeed2=8;
}
keynum=0;
break;
}
}
}
keytime=0;
}
}
void init()
{
TMOD|=0x11;
TH0=(65536-20)/256; //20us
TL0=(65536-20)%256;
TH1=(65536-45872)/256;
TL1=(65536-45872)%256;
EA=1;
ET0=1; //开定时器0中断
ET1=1; //开定时器1中断
TR0=1; //启动定时器0
}
void main()
{
init();
U1=1;
U2=1;
numspeed1=12;
numspeed2=12;
while(1)
{
keyscan();
}
}
void Time0_Init() interrupt 1 //定时器0作用是控制PWM
{
TH0=(65536-20)/256; //20us
TL0=(65536-20)%256;
num1++;
num2++;
if(num1<numspeed1)
U1=1;
else U1=0;
if(num1>20)
num1=0;
if(num2<numspeed2)
U2=1;
else U2=0;
if(num2>20)
num2=0;
}
void Time1_Init() interrupt 3
{
TH1=(65536-45872)/256;
TL1=(65536-45872)%256;
numt++;
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
void keyscan()
{
if(KEY1==0)
{
delayms(10);
if(KEY1==0)
{
while(!KEY1)
{
TR1=1;
}
TR1=0;
keytime=numt;
numt=0;
}
if(keytime>=40)
{
numspeed1=numspeed1+2;
if(numspeed1>16)
numspeed1=8;
keynum=0;
}
if(keytime<40)
{
numspeed1=numspeed1-2;
if(numspeed1<8)
numspeed1=8;
}
keytime=0;
}
if(KEY2==0)
{
delayms(10);
if(KEY2==0)
{
while(!KEY2)
{
TR1=1;
}
TR1=0;
keytime=numt;
numt=0;
}
if(keytime>=40)
{
numspeed2=numspeed2+2;
if(numspeed2>16)
numspeed2=8;
keynum=0;
}
if(keytime<40)
{
numspeed2=numspeed2-2;
if(numspeed2<8)
numspeed2=8;
}
keytime=0;
}
}
一周热门 更多>