两相8拍程序,也是对网上找的程序进行时序修改:
//八拍,半步:(+A)(+B)--(+B)--(-A)(+B)--(-A)--(-A)(-B)--(-B)--(+A)(-B)--(+A)--
int Pin0 = 8; //A
int Pin1 = 9; //A'
int Pin2 = 10; //B
int Pin3 = 11; //B'
int _step =0 ;
boolean dir = true;//正反转
int stepperSpeed = 1500;//电机转速,XX us一步, larger than 1500um
int stepN =0;
void setup()
{
pinMode(Pin0, OUTPUT);
pinMode(Pin1, OUTPUT);
pinMode(Pin2, OUTPUT);
pinMode(Pin3, OUTPUT);
}
void loop()
{
switch(_step){
case 0:
digitalWrite(Pin0, HIGH);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, HIGH);
digitalWrite(Pin3, LOW);
break;
case 1:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, HIGH);
digitalWrite(Pin3, LOW);
break;
case 2:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, HIGH);
digitalWrite(Pin2, HIGH);
digitalWrite(Pin3, LOW);
break;
case 3:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, HIGH);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, LOW);
break;
case 4:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, HIGH);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, HIGH);
break;
case 5:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, HIGH);
break;
case 6:
digitalWrite(Pin0, HIGH);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, HIGH);
break;
case 7:
digitalWrite(Pin0, HIGH);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, LOW);
break;
default:
digitalWrite(Pin0, LOW);
digitalWrite(Pin1, LOW);
digitalWrite(Pin2, LOW);
digitalWrite(Pin3, LOW);
delay(1000);
break;
}
if(dir){
_step++;
}else{
_step--;
}
if(_step>7){
_step=0;
}
if(_step<0){
_step=7;
}
delayMicroseconds(stepperSpeed);
//delay(stepperSpeed);
stepN++;
if(stepN>=400)
{
dir = !dir; //after turning 400 stepps, change direction.
stepN =0;
_step=10;//pause
}
}
结论:
两段程序均可以运行良好,空转时没有丢步。但当时间间隔调小到一定程度后,电机无法转动。四拍时为2000us,八拍时1500微秒。没有细调,可能与负载有关。动力老男孩文章中写的是1500us,但我的电机无法运动,是否和电机型号不同有关。 这个间隔决定了电机的转速,因此这里的步进电机空载转速在四拍时约为2.5转每秒(rps),八拍时约1.67rps。注意:四拍时电机200个脉冲1圈,单步步距1.8度;八拍时400个脉冲1圈,单步步距0.9度。如何进行更高的细分?
步进电机调速主要是调整脉冲频率,所以lm298n的两个pwm波接口EnA、EnB直接接5v。
实验了小角度摆动,摆角9度时,理论可达40*1.67=66.8Hz,以后可以尝试测量是否达到。
当电机不动时,如在loop()中用delay,电机使能,电流很大(超过1A),因此这里将电机停止运动时直接全部置低,电流就很小了(最大电流200ma),但停止时无法保持位置。这一矛盾应该采用闭环控制克服。