Using limit switch for CNC shield v3

Hello Forum,

I am trying to get my end stop switch connected to my CNC shield (v3). I am using an Arduino UNO with a CNC shield v3 and a NEMA 17 0.9degrees per full step and This is the link to the end stop that I am using:

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

int delayTime=15; //Delay between each pause (uS)
long int stps=12800;// 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);


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

    digitalWrite(stepperPin, HIGH);


    digitalWrite(stepperPin, LOW);



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


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

I am trying to use this limit switch to make my stepper motor switch directions while limit switch is pressed. Yet somehow I have the feeling I am doing something wrong concerning the wiring or defining of the limit switch.

Does anyone see a possible error?

That's not even compiling.. missing a closing parenthesis

    if( digitalRead(limitPin) == LOW
       step(true, X_DIR, X_STP, stps);

how are things wired?

Does anyone see a possible error?

Yes. You couldn't be bothered telling us how the limit switch is wired. So, I'm going to guess "incorrectly".

Your code won't even compile, so I won't ask what it actually does, or how that differs from what you want.

I have wired the switch to the X+ pins with OUT to the white pin on X+ and VCC on the black pin. I read somewhere that the ground did not have to be connected. See attachment for visual support.

Black is usually the color code for ground.

Change the pinMode to INPUT_PULLUP.

On the CNC shield all of the black headers on the limit switch header are connected to ground and the white headers are to the limit switch inputs. Wire a normally open contact to the white header and the common contact to the black header and, as MorganS says, enable the internal pull ups.

@MorganS Thank you very much for the solution.
@groundFungus. Thank you for the explanation.

It is very tricky to find these commands when you are, like me, quite new to the whole programming and micro controlling scene.

You both have my gratitude.