Driving Two Stepper Motors at The Same Time
Driving Two Stepper Motors at The Same Time
* Code to control two stepper motors simultaneously using the stepper library
function calls
* This code has functions which make calls to initiate one step from each of the
two motors at a time
* therefore each motor takes it in turn to step with the end result of them both
running together
* the variable 'lastCall' allows for a continuous input to keep the steppers
running if there is no serial input
* Written by Seven Vinton - March 2016 - available and free to use and distribute
in the public domain.
*/
#include <Stepper.h>
//this sets the value for the for loops and therefore sets the amount of steps in
each call
int num_of_steps = 1;
// setup pins for each driver motor1 ~ IN1, IN2, IN3, IN4; motor2 ~ IN1, IN2, IN3,
IN4
Stepper myStepper1(stepsInRev, 4, 5, 6, 7);
Stepper myStepper2(stepsInRev, 8, 9, 10, 11);
// variable to store the last call to the serial port
char lastCall = ' ';
//I had prototyped all of the functions here, but for some reason the Arduino IDE
didn't like it
//so they are coded out until I an figure out why
//void forwardStep();
//void backwardStep();
//void leftStep();
//void rightStep();
//void allStop();
void loop() {
//check to see if there is serial communication and if so read the data
if(Serial.available()) {
char data = (char)Serial.read();
// switch to set the char via serial to a command
switch(data) {
case COMMAND_FORWARD:
forwardStep(num_of_steps);
break;
case COMMAND_BACK:
backwardStep(num_of_steps);
break;
case COMMAND_LEFT:
leftStep(num_of_steps);
break;
case COMMAND_RIGHT:
rightStep(num_of_steps);
break;
case COMMAND_STOP:
allStop();
break;
}
// set the 'lastCall' variable to the last call from the serial
lastCall = data;
}
else{
char data = lastCall;
switch(data) {
case COMMAND_FORWARD:
forwardStep(num_of_steps);
break;
case COMMAND_BACK:
backwardStep(num_of_steps);
break;
case COMMAND_LEFT:
leftStep(num_of_steps);
break;
case COMMAND_RIGHT:
rightStep(num_of_steps);
break;
case COMMAND_STOP:
allStop();
break;
}
lastCall = data;
}
}