0

代码以 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;
}
4

1 回答 1

1

您的代码的以下部分存在问题:

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);
}

这个while循环中的步骤永远不会完成,因为while循环的入口条件与break条件相同。

具体来说,控件只有在digitalRead(LS)返回 a时才会进入 while 循环HIGH,但在它进入 while 循环后,您会再次进行相同的检查,如果函数返回 a HIGH,您将退出 while 循环。这绝不会允许该功能使电机反向运行。

您的代码还有其他几个问题,但这个问题最响亮。

于 2019-04-11T00:08:50.313 回答