The code runs in CW(flex) motion but when switch is detected or hit will not run in CCW(dflex) motion.When the mechanical limit switch is manually pressed or hit the motor will attempt something but it does not stop the CW motion and it definitely does not change its direction to CCW.
Working with bipolar stepper motor that has a 47Gear reduction
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 = angle, tm= time
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;
}