#include <AccelStepper.h>
// Define stepper driver pins
#define STEP_PIN 8
#define DIR_PIN 9
#define BUTTON_PIN 7 // Button for manual activation
// Create stepper motor object using AccelStepper library
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Constants for timing and motor behavior
const unsigned long RUN_TIME = 300000; // 5 minutes in milliseconds (5*60*1000)
const unsigned long SPIN_TIME = 20000; // 20 seconds in milliseconds (20*1000)
const int SPEED = 400; // Maximum stepper speed (steps per second)
const int ACCEL = 200; // Acceleration rate (steps per second²)
bool waitingForButton = false; // Flag to check if we are waiting for a button press
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
stepper.setMaxSpeed(SPEED); // Set maximum speed for the stepper
stepper.setAcceleration(ACCEL); // Set acceleration rate
// Move stepper back and forth for 5 minutes
long startTime = millis(); // Store the current time
while (millis() - startTime < RUN_TIME) { // Run for the specified duration
moveStepper(1000); // Move forward by 1000 steps
moveStepper(-1000); // Move backward by 1000 steps
}
// Stop and wait for button press
waitingForButton = true;
}
void loop() {
// If waiting for button press and button is pressed
if (waitingForButton && digitalRead(BUTTON_PIN) == LOW) {
delay(50); // Short debounce delay
if (digitalRead(BUTTON_PIN) == LOW) { // Confirm button press (still pressed after debounce)
waitingForButton = false; // Disable button waiting state
spinClockwiseWithAcceleration(SPIN_TIME); // Run stepper for 20 seconds
}
}
}
// Function to move the stepper by a given number of steps
void moveStepper(long steps) {
stepper.move(steps); // Set target position
while (stepper.distanceToGo() != 0) { // Keep running until target is reached
stepper.run();
}
}
// Function to spin the motor clockwise with acceleration over a given duration
void spinClockwiseWithAcceleration(long duration) {
// Calculate number of steps required based on speed and duration
// Subtract a small amount (200) to compensate for acceleration overhead
long stepsToMove = (SPEED * (duration / 1000)) - 200;
stepper.move(stepsToMove); // Set target position
// Run the stepper motor until it reaches the target
while (stepper.distanceToGo() != 0) {
stepper.run();
}
}
WIRING IS ONLY ILLUSTRATIONAL