#include <AccelStepper.h>
// Define step constant
#define MotorInterfaceType 4
// Creates an instance
// Pins entered in sequence IN1-IN3-IN2-IN4 for proper step sequence
AccelStepper myStepper(MotorInterfaceType, 8, 10, 9, 11);
// Define the pin for the pushbutton
#define buttonPin 2
// Variable to store the state of the button
int buttonState = 0;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// set the maximum speed, acceleration factor,
// initial speed and the target position
myStepper.setMaxSpeed(1000.0);
myStepper.setAcceleration(50.0);
myStepper.setSpeed(200);
myStepper.moveTo(2038);
// Wait for serial connection
while (!Serial) {
; // Do nothing
}
// Print initialization message
Serial.println("Stepper motor initialized.");
// Set the button pin as input
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Change direction if the button is pressed
if (buttonState == LOW) {
myStepper.moveTo(-myStepper.currentPosition());
Serial.println("Changing direction.");
}
// Move the motor one step
myStepper.run();
// Print current position to serial monitor
Serial.print("Current position: ");
Serial.print(myStepper.currentPosition());
// Print the current speed and direction to the serial monitor
Serial.print(", Speed: ");
Serial.println(myStepper.speed());
// Delay for 1 second before moving again
delay(1000);
}