#include <AccelStepper.h>
const int DIR_PIN = 12;
const int STEP_PIN = 14;
const int ENABLE_PIN = 13;
const int steps_per_rev = 200;
// Define the stepper motor object
AccelStepper stepper(1, DIR_PIN, STEP_PIN);
void setup()
{
Serial.begin(115200);
// Set up motor properties
stepper.setMaxSpeed(3000); // Set your desired maximum speed in steps per second
stepper.setAcceleration(1000); // Set your desired acceleration in steps per second^2
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
pinMode(ENABLE_PIN, OUTPUT);
// Enable the motor (you might need to check if HIGH or LOW enables your specific motor)
digitalWrite(ENABLE_PIN, LOW);
}
void loop()
{
// Move the motor forward
moveStepper(1000, 2000); // Move 1000 steps at a speed of 2000 steps per second
delay(1000);
// Move the motor backward
moveStepper(-1000, 2000); // Move back 1000 steps at a speed of 2000 steps per second
delay(1000);
}
void moveStepper(long steps, float speed)
{
// Set the desired speed and direction based on the sign of 'steps'
if (steps > 0)
stepper.setSpeed(speed); // Set to a positive value for clockwise
else
stepper.setSpeed(-speed); // Set to a negative value for counterclockwise
// Move the motor
stepper.move(steps);
// Run the motor until it reaches the target position
while (stepper.run()) {
// You can add other tasks here if needed
}
}