#include <AccelStepper.h>
// Define motor control pins
#define STEP_PIN 4
#define DIR_PIN 2
#define EN_PIN 5 // Enable pin for the driver
// Define button pin
#define BUTTON_PIN 23
// Create an instance of AccelStepper
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Define variables for max speed and running speed
float maxSpeed = 1000.0; // Maximum speed in steps per second
float accelerationValue = 100; // You can set the acceleration value
long maxSteps = 99999; // maximum movement value
// Button state tracking
bool isRunning = false;
void setup() {
// Initialize pins
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(EN_PIN, OUTPUT);
// Configure the stepper motor
stepper.setMaxSpeed(maxSpeed);
stepper.setAcceleration(accelerationValue); // Set acceleration (adjust as needed)
// Ensure the driver is disabled at startup
digitalWrite(EN_PIN, HIGH); // HIGH disables the driver for most drivers
// Initialize serial monitor for debugging
Serial.begin(115200);
Serial.println("Stepper motor control ready");
}
void loop() {
// Detect button press (falling edge)
// if (digitalRead(BUTTON_PIN) == LOW) {
// digitalWrite(EN_PIN, LOW); // Enable the motor driver
// Serial.println("Motor started");
// stepper.move(maxSteps);
// while (digitalRead(BUTTON_PIN) == LOW) {
// stepper.run();
// }
// Serial.println("Button Released");
// stepper.stop(); // Stop the motor immediately
// stepper.setCurrentPosition(0); // Reset position (optional)
// digitalWrite(EN_PIN, HIGH); // Disable the motor driver
// Serial.println("Motor stopped");
// delay(250); // Debounce delay time for button
// }
static bool buttonPressed = false;
if (digitalRead(BUTTON_PIN) == LOW && !buttonPressed) {
buttonPressed = true;
digitalWrite(EN_PIN, LOW);
Serial.println("Motor started");
stepper.move(maxSteps);
}
if (buttonPressed) {
stepper.run();
if (digitalRead(BUTTON_PIN) == HIGH) {
buttonPressed = false;
stepper.stop();
stepper.setCurrentPosition(0);
digitalWrite(EN_PIN, HIGH);
Serial.println("Button Released");
Serial.println("Motor stopped");
delay(250);
}
}
}