Help needed with coding

I think this is close to what you want:

const int StepsPerRevolution = 200;

const byte DirectionPin = 2;
const byte StepPin = 3;
const byte ButtonPin = 4;
const unsigned long DebounceTime = 10;

boolean ButtonWasPressed = false;
unsigned long ButtonStateChangeTime = 0; // Debounce timer

const unsigned RPM = 60;
const unsigned long MillisecondsPerStep = (60000UL / RPM) / StepsPerRevolution;

void setup()
{
  pinMode(DirectionPin, OUTPUT);
  pinMode(StepPin, OUTPUT);
  pinMode (ButtonPin, INPUT_PULLUP);  // Button between Pin and Ground

  digitalWrite(DirectionPin, HIGH); // Change to LOW if you want the other direction
}

void DoOneRevolution()
{
  for (int i = 0; i < StepsPerRevolution; i++)
  {
    digitalWrite(StepPin, HIGH);
    delay(MillisecondsPerStep / 2);
    digitalWrite(StepPin, LOW);
    delay(MillisecondsPerStep / 2);
  }
}

void loop()
{
  unsigned long currentTime = millis();

  boolean buttonIsPressed = digitalRead(ButtonPin) == LOW;  // Active LOW

  // Check for button state change and do debounce
  if (buttonIsPressed != ButtonWasPressed &&
      currentTime  -  ButtonStateChangeTime > DebounceTime)
  {
    // Button state has changed
    ButtonWasPressed = buttonIsPressed;
    ButtonStateChangeTime = currentTime;

    if (ButtonWasPressed)
    {
      // Button was just pressed
      DoOneRevolution();
    }
  }
}
1 Like