#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
//------8拍-----
uchar code zz[]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09}; //正转
uchar code fz[]={0x09,0x08,0x0c,0x04,0x06,0x02,0x03,0x01}; //反转
sbit K1=P3^0; //停止
sbit K2=P3^1; //正转
sbit K3=P3^2; //反转
sbit K4=P3^3; //加速
sbit K5=P3^4; //减速
uchar state=0; //状态变量
uint Time=60; //延时时间,用于调速
unsigned char receiveData='0';
void UsartConfiguration(); //初始化串口
void delay(uint ms) //延时,用于调速
{
uint t;
while(ms--)
for(t=0;t<120;t++);
}
void motor_zz() //正传函数
{
uint j;
for(j=0;j<8;j++)
{
if(P3==0xfb)
break;
P1=zz[j];
delay(Time);
}
}
void motor_fz() //反转函数
{
uint j;
for(j=0;j<8;j++)
{
if(P3==0xfb)
break;
P1=fz[j];
delay(Time);
}
}
void main()
{
UsartConfiguration();
while(1)
{
while(state==0) //状态0,停止
{
if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
{
state=1;
receiveData='0';
break;
}
if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
{
state=2;
receiveData='0';
break;
}
P0=0xfb;
P1=0x03;
}
while(state==1) //状态1,正转
{
if((K1==0)||(receiveData=='t')) //按下K1或串口接收到'f',电机反转
{
state=0;
receiveData='0';
break;
}
if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
{
state=1;
receiveData='0';
break;
}
if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
{
state=2;
receiveData='0';
break;
}
if((K4==0)||(receiveData=='+')) //按下K4或串口接收到'+',电机加速
{
Time=Time-5;
if(Time<20)
Time=20;
while(K4==0);
}
if((K5==0)||(receiveData=='-')) //按下K5或串口接收到'-',电机减速
{
Time=Time+5;
if(Time>100)
Time=100;
while(K5==0);
}
motor_zz(); //状态1,正转
}
while(state==2) //状态2,反转
{
if((K1==0)||(receiveData=='t')) //按下K1或串口接收到'f',电机反转
{
state=0;
receiveData='0';
break;
}
if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
{
state=1;
receiveData='0';
break;
}
if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
{
state=2;
receiveData='0';
break;
}
if((K4==0)||(receiveData=='+')) //按下K4或串口接收到'+',电机加速
{
Time=Time-5;
if(Time<20)
Time=20;
while(K4==0);
}
if((K5==0)||(receiveData=='-')) //按下K5或串口接收到'-',电机减速
{
Time=Time+5;
if(Time>100)
Time=100;
while(K5==0);
}
motor_fz(); //状态2,反转
}
}
} |