#include <AccelStepper.h>
// Define the stepper motor connections
#define STEP_PIN 2 // Connect this to the STEP pin on the stepper driver
#define DIR_PIN 3 // Connect this to the DIR (direction) pin on the stepper driver
#define BUTTON_PIN 4 // Connect a button to this pin
// Create an instance of the AccelStepper class
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Variable to store the current direction
int currentDirection = 1; // 1 for clockwise, -1 for counterclockwise
void setup() {
// Set up the button pin as an input
pinMode(BUTTON_PIN, INPUT);
// Set the maximum speed and acceleration
stepper.setMaxSpeed(2000.0);
stepper.setAcceleration(1000.0);
// Set the initial position to zero
stepper.setCurrentPosition(0);
// Set the initial direction
stepper.setDirection(currentDirection);
}
void loop() {
// Check if the button is pressed to change the direction
if (digitalRead(BUTTON_PIN) == HIGH) {
// Change the direction
currentDirection *= -1;
stepper.setDirection(currentDirection);
// Wait for the button to be released to avoid rapid direction changes
while (digitalRead(BUTTON_PIN) == HIGH) {
delay(10);
}
}
// Move the stepper motor until it has traveled 1 meter
if (stepper.distanceToGo() == 0) {
// Set the target position to move 1 meter (adjust steps per meter accordingly)
int stepsToMove = 200 * 100; // Assuming 200 steps per revolution and 100 steps per meter
stepper.move(stepsToMove);
}
// Run the stepper motor
stepper.run();
// Check if the motor has reached the target position
if (stepper.distanceToGo() == 0) {
// Motor has reached the target position, stop the motor
stepper.stop();
}
// Delay for a short duration
delay(10);
}