I am working on a project where a digital signal is sent to an Arduino Uno to run a stepper motor forward for a distance and back to its original point. When it reaches the original point it stops. I can get it to do one cycle after I download the program but when I send the start signal again it tries to go the wrong direction. The start signal is controlled by a relay connected to a robot. I also have the power for the stepper on the relay.
#include <AccelStepper.h>
// Define pin connections
const int dirPin = 2;
const int stepPin = 3;
const int start = 4;
// Define motor interface type
#define motorInterfaceType 1
// Creates an instance
AccelStepper myStepper(motorInterfaceType, stepPin, dirPin);
void setup() {
pinMode(start, INPUT);
// set the maximum speed, acceleration factor,
// initial speed and the target position
myStepper.setMaxSpeed(800);
myStepper.setAcceleration(100);
}
void loop() {
// Set the target position:
if (digitalRead(start) == HIGH) {
myStepper.moveTo(5985); // Run to target position with set speed and acceleration/deceleration:
myStepper.run();
if (myStepper.currentPosition() == 5985)
myStepper.moveTo(15);
myStepper.runToPosition();
if (myStepper.distanceToGo() == 0)
myStepper.stop();
}
if (digitalRead(start)==LOW)
myStepper.setCurrentPosition(0);
}