/* Arduino Sketch Controlling Stepper Motor
This code will help us control the stepper motor by setting the maximum speed, acceleration and steps per revolution.
*/
#include <AccelStepper.h> //This library provides useful functions that make it easy to control the stepper motor using Arduino.
//define the digital pins of Arduino we have connected with the DIR and STEP pins of the driver
const int DIR = 6;
const int STEP = 7;
#define motorInterfaceType 1 // Additionally, we will define motor interface type as ‘1’. This means that we are using an external driver that consists of the STEP and DIR pins.
AccelStepper motor(motorInterfaceType, STEP, DIR); // create an instance of the AccelStepper library called motor() and pass motorInterfaceType, STEP and DIR as the three parameters inside it.
void setup() {
Serial.begin(115200); // serial connection between the development board at a baud rate of 115200.
// setting the stepper motor speed to 1000. We will also set the acceleration of the motor using setAcceleration() and pass the acceleration in steps per second per second. The moveTo() method takes in the argument steps per revolution which are 200 as we are using NEMA 17. This will be used to mark our target position.
motor.setMaxSpeed(1000);
motor.setAcceleration(60);
motor.setSpeed(200);
motor.moveTo(400);
}
void loop() {
// rotate the motor in both directions. This will be achieved by keeping track of the target position. If the target position has been reached then another target position will be marked. This will be the same in value as before but with a negative sign. Thus, reversing the direction of the motor. Additionally, we will print when the motor changes direction in the serial monitor as well. The run() method will be responsible to rotate the motor every one step at a time.
if(motor.distanceToGo() == 0){
motor.moveTo(-motor.currentPosition());
Serial.println("Rotating Motor in opposite direction...");
}
motor.run();
}