const byte dirPin = 2, stepPin = 3, buttonPin = 4, ledPin = 5;
bool pulseState = 0;  // HIGH or LOW for stepper half "step"

unsigned long buttonTimer, buttonTimeout = 50;  // milliseconds
unsigned long motorTimer, motorTimeout = 1000;  // microseconds

bool lastButtonRead, currentButtonState;

void setup() {
  Serial.begin(11520);

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(ledPin, OUTPUT);

  digitalWrite(dirPin, HIGH);
}

void loop() {
  stepMotor();
  readButton();
}

void stepMotor() {
  if (micros() - motorTimer > motorTimeout) {  // wait for next step
    motorTimer = micros();                     // reset timer
    pulseState = !pulseState;           // invert motor pulse state
    digitalWrite(stepPin, pulseState);  // change motor pulse state
  }
}

void readButton() {
  bool currentButtonRead = digitalRead(buttonPin);  // read button pin

  if (currentButtonRead != lastButtonRead) {  // if button pin changes...
    buttonTimer = millis();                   // ...start a timer
    lastButtonRead = currentButtonRead;       // ... and store current state
  }

  if ((millis() - buttonTimer) > buttonTimeout) {               // if button change was longer than debounce timeout
    if (currentButtonState == HIGH && lastButtonRead == LOW) {  // ... state "NOT pressed" while button "IS PRESSED"
      //==================================================
      digitalWrite(dirPin, !digitalRead(dirPin));  // change direction
      digitalWrite(ledPin, !digitalRead(ledPin));  // chaange LED
      //==================================================
    }
    currentButtonState = currentButtonRead;  // update button state
  }
}
A4988