#include <AccelStepper.h>
// Pin Definitions
#define DIR_PIN 3
#define STEP_PIN 2
#define BUTTON_1 4 // Move forward X steps
#define BUTTON_2 5 // Move back to 0
#define BUTTON_3 6 // Start/stop continuous forward/backward movement
// Parameters
const int X_STEPS = 200; // Steps to move forward/backward
const int DEBOUNCE_DELAY = 10; // Debounce delay in ms
// Create AccelStepper object
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Variables
unsigned long lastButtonPress = 0;
bool continuousMode = false; // Tracks if continuous mode is active
bool movingForward = true; // Tracks direction in continuous mode
void setup() {
pinMode(BUTTON_1, INPUT_PULLUP);
pinMode(BUTTON_2, INPUT_PULLUP);
pinMode(BUTTON_3, INPUT_PULLUP);
stepper.setMaxSpeed(2000); // Max speed (steps/sec)
stepper.setAcceleration(1000); // Acceleration (steps/sec^2)
stepper.setCurrentPosition(0); // Set starting position to 0
}
void loop() {
stepper.run(); // Ensure the motor keeps running smoothly
// Check for button presses with debounce
if (millis() - lastButtonPress > DEBOUNCE_DELAY) {
if (digitalRead(BUTTON_1) == LOW && stepper.currentPosition() == 0) {
moveMotor(X_STEPS); // Move forward X steps
}
else if (digitalRead(BUTTON_2) == LOW && stepper.currentPosition() == X_STEPS) {
moveMotor(-X_STEPS); // Move back to 0
}
else if (digitalRead(BUTTON_3) == LOW) {
toggleContinuousMode(); // Toggle continuous mode
}
}
// Handle continuous movement if active
if (continuousMode && stepper.distanceToGo() == 0) {
moveMotor(movingForward ? X_STEPS : -X_STEPS); // Alternate direction
movingForward = !movingForward; // Toggle direction
}
}
// Move motor to a relative target
void moveMotor(int steps) {
stepper.move(steps); // Set relative target position
lastButtonPress = millis(); // Update debounce time
}
// Toggle continuous forward/backward movement
void toggleContinuousMode() {
continuousMode = !continuousMode; // Toggle mode
lastButtonPress = millis(); // Update debounce time
if (!continuousMode) {
// If stopping, return to the starting position
stepper.moveTo(0); // Absolute target: position 0
}
}