Using magnetic contact switches with linear actuator

Hey all,
Just wondering if someone could shed some light on my situation. I am trying to control a 12 V linear actuator with Arduino Uno and Adafruit Motor Shield. I want to use magnetic contact switches to stop the forward and backward motion. I want the linear actuator to go 15 cycles between the magnetic contact switches. Here is the code I am using:
#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
int x;
int sensorPin = 14;
int magnetSensor;
int magnetSensor2;
int sensorPin2 = 15;
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println(“Motor test!”);
Serial.begin(9600);
pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, HIGH);

for(x=0;x<2;x++){
motor.setSpeed(200); // set the speed to 200/255
motor.run(FORWARD); // turn it on going forward
magnetSensor = digitalRead(sensorPin); // find out switch state by reading input pin
if(magnetSensor == HIGH){
motor.run(RELEASE); // stopped;
}
else{
motor.run(FORWARD); // the other way
}
delay(200);

magnetSensor = digitalRead(sensorPin2); // find out switch state by reading input pin
if(magnetSensor2 == HIGH){
motor.run(RELEASE); // stopped;
}
else{
motor.run(BACKWARD); // the other way
}
delay(200);
}}

void loop() {
Serial.print(“tick”);

}

And what's happening?

Basically, I was testing the linear actuator with the contact switches. When the switches, made contact the linear actuator just continued to move. I am assuming it is not recognizing when the switch makes contact. I was thinking about using an interrupt but am unsure how to use it.

You are not setting this pin in setup() int sensorPin2 = 15; You don't have much in loop() which is where the sketch runs over and over as opposed to setup() which only runs at reset (once).

Ok, I will try the setting the integer in the setup. I put the code in a for loop in the setup because I only wanted the code to run 15 times. I thought the code would continue to run in the loop() if it was placed there.

Yes, do this. pinMode(sensorPin2, INPUT); digitalWrite(sensorPin2, HIGH);

I put the code in a for loop in the setup because I only wanted the code to run 15 times.

That is reasonable. How are you telling it to cycle 15 times?

LarryD: Yes, do this. pinMode(sensorPin2, INPUT); digitalWrite(sensorPin2, HIGH);

These days the idiom is

  pinMode (sensorPin2, INPUT_PULLUP) ;

which works across all Arduinos, not just Atmel based ones (although it does exactly the same here).

That portion of code appears to fix some problems, but the contacts are still struggling to work right. I wanted to use the for loop to operate 15 times.