#include <AccelStepper.h>
const byte dirPin = 4;
const byte stepPin = 5;
const byte potPin = A0;

AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
long speed = 100;
long direction = 1;

void checkPot() {
  int potValue = analogRead(potPin);
  int newDirection = direction;
  if (potValue < 340) newDirection = -1;
  else if (potValue < 680) newDirection = 0;
  else newDirection = 1;
  if (newDirection != direction) {
    direction = newDirection;
    Serial.print("New speed = "); Serial.println(direction * speed);
    stepper.setSpeed(direction * speed);
  }
}

void checkSerialForSpeed() {
  static long newSpeed = 0;
  int r = Serial.read();
  switch (r) {
    case '0'...'9':
      newSpeed = newSpeed * 10 + r - '0';
      break;

    case '\n':
      speed = newSpeed;
      newSpeed = 0;
      Serial.print("New speed = "); Serial.println(direction * speed);
      stepper.setSpeed(direction * speed);
      break;

    default: break; // ignore anything else
  }
}

void setup() {
  stepper.setMaxSpeed(10000);
  Serial.begin(115200);
  Serial.println("Ready");
}

void loop() {
  checkPot();
  checkSerialForSpeed();
  stepper.runSpeed();
}
A4988