CODE
// Stepper Pins
const int stepPin = 5;
const int dirPin = 2;
const int enPin = 8;
// Buttons
const int btnCW = 9;
const int btnCCW = 10;
const int btnSTOP = 11;
// Potentiometer
const int potPin = A0;
int speedDelay = 500;
bool motorRunning = false;
bool direction = HIGH;
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
pinMode(btnCW, INPUT_PULLUP);
pinMode(btnCCW, INPUT_PULLUP);
pinMode(btnSTOP, INPUT_PULLUP);
digitalWrite(enPin, LOW); // enable driver
}
void loop() {
// Speed control
int potValue = analogRead(potPin);
speedDelay = map(potValue, 0, 1023, 100, 1000);
// Button press detect (one click)
if (digitalRead(btnCW) == LOW) {
direction = HIGH;
motorRunning = true;
delay(20); // debounce
}
if (digitalRead(btnCCW) == LOW) {
direction = LOW;
motorRunning = true;
delay(20);
}
if (digitalRead(btnSTOP) == LOW) {
motorRunning = false;
delay(20);
}
// Run motor if enabled
if (motorRunning) {
digitalWrite(dirPin, direction);
stepMotor();
}
}
// Step function
void stepMotor() {
digitalWrite(stepPin, HIGH);
delayMicroseconds(speedDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(speedDelay);
}
