代码以 CW(flex) 运动运行,但当检测到开关或被击中时不会以 CCW(dflex) 运动运行。当手动按下或击中机械限位开关时,电机将尝试执行某些操作,但不会停止 CW 运动,并且它绝对不会将其方向更改为 CCW。
使用具有 47Gear 减速的双极步进电机
const int LS = 2; // input pin for the Limit Switch
int detectState = 0; // Variable for reading the encoder status
const int stepPin = 5;
const int dirPin = 4;
const int enablePin = 3;
double GReduction = 47;
int T1 = 100;
int T2 = 100;
int Z = 0;
int Walk_flag = 1;
double angle = 0;
///////////////////////////////////////flex(int ang,int tm); // an = 角度, tm= 时间
void setup()
{
pinMode(LS, INPUT); //Set pin 2 as input
pinMode(stepPin,OUTPUT); //Set pin 5 as input
pinMode(dirPin,OUTPUT);//Set pin 4 as input
pinMode(enablePin,OUTPUT);//Set pin 3 as input
attachInterrupt(digitalPinToInterrupt(LS), LS_Hit, CHANGE);
////////////homing algorithm
//T1=100;
dflex();
Serial.begin(9600);
angle=0;
flex(90,1);
}
void loop() {
flex(30,100);
delay(1000);
if( detectState==HIGH)
{
dflex();
}
}
///////////////////////////////////// CW motion
void flex(int ang,int tm) // an = angle, tm= time
{
double ZZ;
ZZ= (800.0*ang*GReduction/360.0);
//String val = String(ang/360);
Serial.println(ang);
for(int x = 0; x <ZZ; x++) { //angle control
digitalWrite(dirPin,HIGH);
digitalWrite(enablePin,HIGH);
digitalWrite(stepPin,HIGH);
delayMicroseconds(T1);
digitalWrite(stepPin,LOW);
delayMicroseconds(T1);
}
digitalWrite(enablePin,LOW);
}
/////////CCW motion
void dflex()
{
digitalWrite(enablePin,HIGH);
digitalWrite(dirPin,LOW); //Changes the rotations direction
int LS_status=digitalRead(LS);
while(digitalRead(LS)) {
if(digitalRead(LS)==HIGH)
{
break;
}
digitalWrite(stepPin,HIGH);
delayMicroseconds(T2);
//delay(100/T); // One second delay
digitalWrite(stepPin,LOW);
//delay(T/100); // One second delay
delayMicroseconds(T2);
}
}
void LS_Hit()
{
digitalWrite(enablePin,LOW);
angle=0;
detectState =! detectState;
}