// === Пины подключения ===
const int stepPin = 3;     // Пин STEP на A4988
const int dirPin  = 4;     // Пин DIR на A4988
const int enPin   = 5;     // Пин EN (можно заземлить напрямую)

const int btnStartPin = 6; // Кнопка Start/Stop
const int btnLeftPin  = 7; // Кнопка "влево"
const int btnRightPin = 8; // Кнопка "вправо"

const int potPin = A0;     // Потенциометр скорости

// === Переменные состояния ===
bool motorEnabled = false;
int direction = HIGH; // HIGH — вправо, LOW — влево
unsigned long lastStepTime = 0;
unsigned long stepDelay = 1000; // мкс

// === Антидребезг кнопок ===
unsigned long lastDebounceTimeStart = 0;
unsigned long lastDebounceTimeLeft = 0;
unsigned long lastDebounceTimeRight = 0;
const unsigned long debounceDelay = 50;

bool lastStartBtnState = HIGH;
bool lastLeftBtnState = HIGH;
bool lastRightBtnState = HIGH;

void setup() {
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(enPin, OUTPUT);

  pinMode(btnStartPin, INPUT_PULLUP);
  pinMode(btnLeftPin, INPUT_PULLUP);
  pinMode(btnRightPin, INPUT_PULLUP);

  digitalWrite(enPin, LOW); // Включаем драйвер (LOW = активен)
  digitalWrite(dirPin, direction);
}

void loop() {
  readButtons();
  adjustSpeed();

  if (motorEnabled) {
    rotateMotor();
  }
}

// === Чтение кнопок с антидребезгом ===
void readButtons() {
  handleButton(btnStartPin, lastStartBtnState, lastDebounceTimeStart, toggleMotor);
  handleButton(btnLeftPin, lastLeftBtnState, lastDebounceTimeLeft, []() {
    direction = LOW;
    digitalWrite(dirPin, direction);
  });
  handleButton(btnRightPin, lastRightBtnState, lastDebounceTimeRight, []() {
    direction = HIGH;
    digitalWrite(dirPin, direction);
  });
}

void handleButton(int pin, bool &lastState, unsigned long &lastTime, void (*onPress)()) {
  bool reading = digitalRead(pin);

  if (reading != lastState && (millis() - lastTime > debounceDelay)) {
    lastTime = millis();
    lastState = reading;
    if (reading == LOW) {
      onPress();
    }
  }
}

// === Функции управления ===
void toggleMotor() {
  motorEnabled = !motorEnabled;
}

void adjustSpeed() {
  int potVal = analogRead(potPin); // 0–1023
  stepDelay = map(potVal, 0, 1023, 2000, 100); // скорость: от медленно до быстро
}

void rotateMotor() {
  unsigned long now = micros();
  if (now - lastStepTime >= stepDelay) {
    lastStepTime = now;

    digitalWrite(stepPin, HIGH);
    delayMicroseconds(2); // короткий импульс
    digitalWrite(stepPin, LOW);
  }
}

A4988