/*
  Stepper with buttons demo
  Written for A4988 but works with most stepper drivers
  Wokwi | questions
  Help making a step motor control via push buttons with arduino
  alo - Saturday, October 25, 2025 1:04 AM
  Can someone help me making the connections pls. I dont understand them
  https://learn.sparkfun.com/tutorials/easy-driver-hook-up-guide
*/
#include <AccelStepper.h>
// user constants
const int NUM_BTNS = 2;
const long MOVE_STEPS     = 400;
const float MAX_SPEED     = 400.0;
const float ACCELERATION  = 200.0;
// pin constants
const int DIR_PIN  = 2;
const int STEP_PIN = 3;
const int ENABLE_PIN = 4;
const int BTN_PINS[] = {6, 5};
int oldBtnState[NUM_BTNS];
AccelStepper stepper(AccelStepper::DRIVER, STEP_PIN, DIR_PIN);
int checkButtons()  {
  // function returns which button was pressed, 0 if none, -1 if released
  int btnPressed = 0;
  for (int i = 0; i < NUM_BTNS; i++) {
    // check each button
    int  btnState = digitalRead(BTN_PINS[i]);
    if (btnState != oldBtnState[i])  { // if it changed
      oldBtnState[i] = btnState;       // remember state for next time
      if (btnState == LOW)  {          // was just pressed
        btnPressed = i + 1;
        //Serial.print("Button ");
        //Serial.print(btnPressed);
        //Serial.println(" pressed");
      } else {                            // was just released
        btnPressed = -1;
        //Serial.print("Button ");
        //Serial.print(i + 1);
        //Serial.println(" released");
      }
      delay(20);  // debounce
    }
  }
  return btnPressed;
}
void setup() {
  Serial.begin(9600);
  pinMode(ENABLE_PIN, OUTPUT);
  for (int i = 0; i < NUM_BTNS; i++)  {
    pinMode(BTN_PINS[i], INPUT_PULLUP);
  }
  digitalWrite(ENABLE_PIN, LOW); // Enable driver
  stepper.setMaxSpeed(MAX_SPEED);
  stepper.setAcceleration(ACCELERATION);
  Serial.println("Stepper control started");
}
void loop() {
  int btnNum = checkButtons();
  if (btnNum == 1) {
    Serial.println("Rotate counter clockwise");
    stepper.moveTo(-MOVE_STEPS);
  } else if (btnNum == 2) {
    Serial.println("Rotate clockwise");
    stepper.moveTo(MOVE_STEPS);
  }
  stepper.run();
  if (stepper.distanceToGo() == 0) {
    stepper.setCurrentPosition(0);
  }
}
CCW
CW