步进电机的正反转的关键在于相序,改变相序即改变旋转的方向。
例如四相八拍:A-AB-B-BC-C-CD-D-DA(正转)
D-DC-C-CB-B-BA-A-AD(反转)
通过按键控制电机的正反转:(为了更容易理解,程序写的有点多,当然,如果为了减少代码,可以利用数组来简化程序)
#include "reg52.h"
typedef unsigned char u8;
typedef unsigned int u16;
sbit A = P1^0; //定义引脚
sbit b = P1^1;
sbit C = P1^2;
sbit D = P1^3;
void setmotor0();
void setmotor1();
void motor_cs();
void Timer0Init();
void Delay10ms();
void key1();
void key();
sbit key_1=P3^4;
sbit key_2=P3^5;
u8 rate=0,i=0,m=0;
u8 motorstep=0; //步进电机步序
u16 Speed=1,Tim,CT;
#define speed 12;
void Timer0() interrupt 1
{ static u16 count,count1;
TH0=0xfc;
TL0=0x18;
count++;
if(count>=100)
{
count=0;
if(i==0) {count1=90;}
if(i==1) {count1=60;}
if(i==2) {count1=30;}
if(i==3) {count1=0;}
if(i>3) i=0;
}
if(count<=count1) Tim=1; else Tim=0;
}
int main()
{
Timer0Init();
motor_cs();
while(1)
{
key();
key1();
if(m==0) setmotor0();
//if(m==1) Tim=0;
if(m==1) setmotor1();
if(m>=2) {m=0;setmotor0();}
//if(m==3) Tim=0;
//if(m>=4) {m=0; setmotor0();}
}
}
void motor_cs()
{
A=1;
b=1;
C=1;
D=1;
}
void setmotor0()
{
switch(motorstep)
{
case 0: //a
if(Tim)
{
A=0;
b=1;
C=1;
D=1;
motorstep=1;
Tim=0;
}
break;
case 1: //ab
if(Tim)
{
A=0;
b=0;
C=1;
D=1;
motorstep=2;
Tim=0;
}
break;
case 2:
if(Tim)
{
A=1;
b=0;
C=1;
D=1;
motorstep=3;
Tim=0;
}
break;
case 3:
if(Tim)
{
A=1;
b=0;
C=0;
D=1;
motorstep=4;
Tim=0;
}
break;
case 4:
if(Tim)
{
A=1;
b=1;
C=0;
D=1;
motorstep=5;
Tim=0;
}
break;
case 5:
if(Tim)
{
A=1;
b=1;
C=0;
D=0;
motorstep=6;
Tim=0;
}
break;
case 6:
if(Tim)
{
A=1;
b=1;
C=1;
D=0;
motorstep=7;
Tim=0;
}
break;
case 7:
if(Tim)
{
A=0;
b=1;
C=1;
D=0;
motorstep=0;
Tim=0;
}
break;
}
}
void setmotor1()
{
switch(motorstep)
{
case 0: //a
if(Tim)
{
A=0;
b=1;
C=1;
D=0;
motorstep=1;
Tim=0;
}
break;
case 1: //ab
if(Tim)
{
A=1;
b=1;
C=1;
D=0;
motorstep=2;
Tim=0;
}
break;
case 2:
if(Tim)
{
A=1;
b=1;
C=0;
D=0;
motorstep=3;
Tim=0;
}
break;
case 3:
if(Tim)
{
A=1;
b=1;
C=0;
D=1;
motorstep=4;
Tim=0;
}
break;
case 4:
if(Tim)
{
A=1;
b=0;
C=0;
D=1;
motorstep=5;
Tim=0;
}
break;
case 5:
if(Tim)
{
A=1;
b=0;
C=1;
D=1;
motorstep=6;
Tim=0;
}
break;
case 6:
if(Tim)
{
A=0;
b=0;
C=1;
D=1;
motorstep=7;
Tim=0;
}
break;
case 7:
if(Tim)
{
A=0;
b=1;
C=1;
D=1;
motorstep=0;
Tim=0;
}
break;
}
}
void Timer0Init()
{
TMOD=TMOD|0X01;
TH0=0xfc;
TL0=0x18;
ET0=1;
EA=1;
TR0=1;
}
void key()
{
if(key_1==0)
{
Delay10ms();
if(key_1==0)
i++;
}
while(!key_1);
}
void key1()
{
if(key_2==0)
{
Delay10ms();
if(key_2==0)
m++;
}
while(!key_2);
}
void Delay10ms() //@11.0592MHz
{
unsigned char i, j;
i = 18;
j = 235;
do
{
while (--j);
} while (--i);
}