#define PIN_DIR 27
#define PIN_STEP 14
#define PIN_SWITCH 18

#define RATIO_STEPS_PER_MM 10

int x = 0;

void setup() {
  pinMode(PIN_DIR, OUTPUT);
  pinMode(PIN_STEP, OUTPUT);
  pinMode(PIN_SWITCH, INPUT_PULLUP);
  digitalWrite(PIN_STEP, LOW);
  digitalWrite(PIN_DIR, LOW);
  home();
}

void step(){
  digitalWrite(PIN_STEP, HIGH);
  delayMicroseconds(500);
  digitalWrite(PIN_STEP, LOW);
  delayMicroseconds(500);
  delay(50);
}

void home(){
  digitalWrite(PIN_DIR, LOW);
  while(digitalRead(PIN_SWITCH)){
    step();
  }
  x = 0;
}

void move(int millimeters){
  auto steps_count = abs(millimeters *RATIO_STEPS_PER_MM);
  digitalWrite(PIN_DIR, millimeters > 0);
  for(int i = 0; i < steps_count; i++){
    step();
  }
  x += millimeters;
}

void loop() {
  move(50);
  delay(2000);
  move(-20);
  while(1);
}
A4988