Limit switch code

Hello everyone. I am new to forum and arduino programmiring.
Right now I am working on my biggest project so far and I need help. I am using arduino UNO, Arduino CNC sheield V3 limit switch named tiaihua and stepper motor Nema 17 bipolar. All I want is for the motor to spin until it reaches the limit switch. When the limit switch is activated, the motor would simply change direction and rotate again all the way to the second limit switch where it would do the same. I don't know where I have mistake, please help.

#define EN        8 
#define X_DIR     5
#define X_STP     2

int delayTime=1500; //Delay between each pause (uS)
long int stps=4000;// microsteps per revolution with 1/32 microstepping
const int limitPin = 9; //enable limitPin

void step(boolean dir, byte dirPin, byte stepperPin, long int steps)

{

  digitalWrite(dirPin, dir);

  delay(1000);

  for (long int i = 0; i < steps; i++) {

    digitalWrite(stepperPin, HIGH);

    delayMicroseconds(delayTime);

    digitalWrite(stepperPin, LOW);

    delayMicroseconds(delayTime);

  }
}

void setup() {
pinMode(X_DIR, OUTPUT);
pinMode(X_STP, OUTPUT);
pinMode(EN, OUTPUT);
pinMode(limitPin, INPUT_PULLUP);
digitalWrite(EN, LOW);

}

void loop() {
 if( digitalRead(limitPin) == HIGH){
    step(false, X_DIR, X_STP, stps);
   if( digitalRead(limitPin) == LOW)
   {
       step(true, X_DIR, X_STP, stps);
    }
 }
}

limit switch is wired to end stops pin X+ (red and blach-C and ND)

And what do you perceive that little mistake to be?

The fact that you're not monitoring the limit switch while you're stepping?

First problem is that my limit switch don't even have a function. When the motor is spining and when i click the limit switch nothing happend. because of that i think i have a problem in code

Test your limit switch

(uncompied, untested)

const int limitPin = 9;

void setup() 
{
  Serial.begin (115200);
  pinMode(limitPin, INPUT_PULLUP);
}

void loop() 
{
  Serial.println (digitalRead (limitPin) == HIGH ? "HIGH" : "LOW");
}

why don't you check the indentation of your code

I tested the switch and it's working

does the code work? (check indentation)

So, why not read it while you're stepping?

If the code is working? I am new it that and yeah how can i check that :confused:

Get creative. Try stuff.
Test the limit switch in your for loop.
If the switch is closed, break out of the loop.

I try now few things and all is working now. thanks for all

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.