Hi everyone,
Im currently working on a project that involves a cart in a rail using an Arduino Mega, external battery, 2 28BYJ stepper motors with ULN2003 drivers. On the ends it has 2 micro limit switches on NC and COM. The code "works"if the limit switch is pressed by hand the motors change direction, BUT in the cart, the cart moves so slow that when the limit switch is pressed, it keeps on pressing and it doesn't trigger changing the direction, so it keeps moving forward.
This is a video of the problem:
Any ideas on how to fix this?
This is my code:
// Include the AccelStepper Library
#include <AccelStepper.h>
// Define step constants
#define FULLSTEP 4
// Creates two instances
// Pins entered in sequence IN1-IN3-IN2-IN4 for proper step sequence
AccelStepper stepper1(FULLSTEP, 8, 10, 9, 11);
AccelStepper stepper2(FULLSTEP, 4, 6, 5, 7);
//Limit switches
#define LIMIT_SWITCH_PIN_L 2
#define LIMIT_SWITCH_PIN_R 3
void setup() {
Serial.begin(9600);
pinMode(LIMIT_SWITCH_PIN_L, INPUT_PULLUP);
pinMode(LIMIT_SWITCH_PIN_R, INPUT_PULLUP);
// set the maximum speed, acceleration factor,
// initial speed and the target position for motor 1
stepper1.setMaxSpeed(100.0);
stepper1.setAcceleration(100.0);
stepper1.setSpeed(100);
stepper1.moveTo(2560);
// set the same for motor 2
stepper2.setMaxSpeed(100.0);
stepper2.setAcceleration(100.0);
stepper2.setSpeed(100);
stepper2.moveTo(-2560);
delay(100);
}
void loop() {
if (stepper1.distanceToGo() == 0 || stepper2.distanceToGo() == 0){
stepper1.moveTo(stepper1.currentPosition());
stepper2.moveTo(-stepper2.currentPosition());
}
if (stepper1.distanceToGo() == 0 || stepper2.distanceToGo() == 0){
stepper1.moveTo(-stepper1.currentPosition());
stepper2.moveTo(stepper2.currentPosition());
}
if (digitalRead(LIMIT_SWITCH_PIN_R) == 1){
stepper1.stop();
stepper2.stop();
Serial.println("Right limit switch pressed");
stepper1.moveTo(2560);
stepper2.moveTo(-2560);
delay(100);
}
if (digitalRead(LIMIT_SWITCH_PIN_L) == 1){
stepper1.stop();
stepper2.stop();
Serial.println("Left limit switch pressed");
stepper1.moveTo(-2560);
stepper2.moveTo(2560);
delay(100);
}
stepper1.run();
stepper2.run();
}