// https://forum.arduino.cc/t/running-two-stepper-motors-at-once/1115352
#include <AccelStepper.h>
#define dirPinLeft 7 /// direction left
#define stepPinLeft 8 /// step left
#define dirPinRight 3 /// direction right
#define stepPinRight 4 /// step right
#define motorInterfaceType 1 /// bipolar motor
AccelStepper stepperLeft = AccelStepper(motorInterfaceType, stepPinLeft, dirPinLeft);
AccelStepper stepperRight = AccelStepper(motorInterfaceType, stepPinRight, dirPinRight);
const int enPin1 = 9; /// enable pin 1
const int enPin2 = 10; /// enable pin 2
const int buttonPin = 5; /// button pin
int buttonState = 0; /// variable for reading the pushbutton status
int processEnablerStateVariableCount = 5; // global state variable for remembering how many times to go
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Button between Pin and Ground
pinMode(enPin1, INPUT);
pinMode(enPin2, INPUT);
digitalWrite(buttonPin, HIGH); /// activate arduino internal pull up
digitalWrite(enPin1, HIGH); /// disable motor control
digitalWrite(enPin2, HIGH); /// disable motor control
stepperLeft.setMaxSpeed(100); /// slow is 100, fast is 900000
stepperLeft.setAcceleration(50);
stepperLeft.moveTo(15);
stepperRight.setMaxSpeed(100);
stepperRight.setAcceleration(50);
stepperRight.moveTo(-15);
}
void loop() {
slowMove1();
}
void slowMove1() { /// motors are NOT disabled at end of function
digitalWrite(enPin1, LOW); /// enable motor control
digitalWrite(enPin2, LOW); /// enable motor control
if (stepperLeft.distanceToGo() == 0 && processEnablerStateVariableCount > 0) {
stepperLeft.moveTo(-stepperLeft.currentPosition());
--processEnablerStateVariableCount; /// reduce the count by one
}
stepperLeft.run();
if (stepperRight.distanceToGo() == 0 && processEnablerStateVariableCount > 0) {
stepperRight.moveTo(-stepperRight.currentPosition());
}
stepperRight.run();
digitalWrite(enPin1, HIGH); /// disable motor control
digitalWrite(enPin2, HIGH); /// disable motor control
}