#include <AccelStepper.h>
#define MOTOR_STEP_PIN 2
#define MOTOR_DIR_PIN 3
#define FORWARD_BTN_PIN 16
#define REVERSE_BTN_PIN 17
#define RUN_TIME 7000 // 7 seconds in milliseconds
AccelStepper stepper = AccelStepper(AccelStepper::DRIVER, MOTOR_STEP_PIN, MOTOR_DIR_PIN);
unsigned long startTime = 0;
void setup() {
pinMode(FORWARD_BTN_PIN, INPUT_PULLUP);
pinMode(REVERSE_BTN_PIN, INPUT_PULLUP);
stepper.setMaxSpeed(500);
stepper.setAcceleration(500);
}
void loop() {
if (digitalRead(FORWARD_BTN_PIN) == LOW && millis() - startTime > RUN_TIME) {
startTime = millis();
stepper.setCurrentPosition(0); // Reset position to simulate direction change
stepper.setSpeed(500); // Set speed for forward rotation
while ((millis() - startTime) < RUN_TIME) {
stepper.run(); // Run the motor forward
}
stepper.stop();
} else if (digitalRead(REVERSE_BTN_PIN) == LOW && millis() - startTime > RUN_TIME) {
startTime = millis();
stepper.setCurrentPosition(0); // Reset position to simulate direction change
stepper.setSpeed(-500); // Set negative speed for reverse rotation
while ((millis() - startTime) < RUN_TIME) {
stepper.run(); // Run the motor in reverse
}
stepper.stop();
}
}