Potentiometer with reverse button for stepper

Haha. Same project here >>

Just for that, here's my code dump.

#define potPin A0
#define dirPin 3
#define stepPin 4

int dir, step, deadband = 100;

void setup() {
  Serial.begin(115200);
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);

  welcome();
  while (analogRead(potPin) < 490 || analogRead(potPin) > 534) {} // wait for potentiometer near zero
  instructions();
}

void loop() {
  int speed = map(analogRead(A0), 0, 1024, -2000, 2000);
  if (speed <= -deadband) {
    dir = 0; // counterclockwise
    motorStep(dir, speed);
  }
  if (speed >= deadband) {
    dir = 1; // clockwise
    motorStep(dir, speed);
  }
  if (abs(speed) < deadband) // deadband - stop motor
    motorStop(speed);
}

void motorStep(int dir, int speed) {
  digitalWrite(dirPin, dir);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(2000 - abs(speed));
  digitalWrite(stepPin, LOW);
  // delayMicroseconds(2000 - abs(speed)); // only the HIGH pulse duration is needed
}

void motorStop(int speed) {
  digitalWrite(stepPin, LOW);
  delayMicroseconds(2000);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(2000);
}

void motorDisplay(int dir, int speed) {
  Serial.print("DIRECTION: ");
  Serial.print((dir == 1) ? " CW" : "CCW");
  Serial.print(" SPEED: ");
  Serial.println(abs(speed));
}

void welcome() {
  Serial.print("Motor will start when potentiometer is at ZERO.  ");
}

void instructions() {
  Serial.println("Motor is started.");
  Serial.println("<< LEFT to increase CCW  | CENTER to STOP | RIGHT to increase CW >>");
}
1 Like