#include <AccelStepper.h>
// Pin definitions (based on your Wokwi diagram or customization)
#define STEP_PIN 10
#define DIR_PIN A3
#define ENABLE_PIN A2
#define BTN_HOME 2 // Button 1: Go to position 0
#define BTN_FORWARD 3 // Button 2: Move forward by N steps
AccelStepper motor(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
// Number of steps to move when forward button is pressed
const int stepDistance = 200;
void setup() {
pinMode(ENABLE_PIN, OUTPUT);
digitalWrite(ENABLE_PIN, LOW); // Enable driver
pinMode(BTN_HOME, INPUT_PULLUP);
pinMode(BTN_FORWARD, INPUT_PULLUP);
motor.setMaxSpeed(1000);
motor.setAcceleration(500);
}
void loop() {
motor.run(); // Keep motor moving to target
if (digitalRead(BTN_HOME) == LOW) {
// Debounce delay
delay(50);
if (digitalRead(BTN_HOME) == LOW) {
motor.moveTo(0); // Go to position zero
while (motor.distanceToGo() != 0) {
motor.run();
}
}
}
if (digitalRead(BTN_FORWARD) == LOW) {
// Debounce delay
delay(50);
if (digitalRead(BTN_FORWARD) == LOW) {
// Move forward by defined steps
motor.moveTo(motor.currentPosition() + stepDistance);
while (motor.distanceToGo() != 0) {
motor.run();
}
}
}
}