// Pin assignments..
const int dirPin = 10; // Direction pin
const int stepPin = 11; // Step pin
const int enablePin = 12; // Enable pin
const int forwardButton = 9; // Forward button pin
const int reverseButton = 8; // Reverse button pin
const int stopButton = 5; // Stop button pin
// Variables
bool isRunning = false;
bool direction = true; // true = forward, false = reverse
unsigned long stepDelay = 500; // Initial step delay (speed control)
void setup() {
// Initialize pins
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW); // Enable stepper driver
// Initialize buttons with internal pull-ups
pinMode(forwardButton, INPUT_PULLUP);
pinMode(reverseButton, INPUT_PULLUP);
pinMode(stopButton, INPUT_PULLUP);
// Initialize Serial communication for speed control
Serial.begin(9600);
Serial.println("Enter step delay (in microseconds): ");
}
void loop() {
// Check button states
if (digitalRead(forwardButton) == LOW) {
direction = true;
isRunning = true;
}
if (digitalRead(reverseButton) == LOW) {
direction = false;
isRunning = true;
}
if (digitalRead(stopButton) == LOW) {
isRunning = false;
}
// Read Serial input to update speed control
if (Serial.available() > 0) {
String input = Serial.readStringUntil('\n');
unsigned long newDelay = input.toInt(); // Convert the input to a number
if (newDelay > 0) { // Ensure a valid number is entered
stepDelay = newDelay;
Serial.print("Updated step delay to: ");
Serial.println(stepDelay);
}
}
// Control motor direction and movement
if (isRunning) {
digitalWrite(dirPin, direction); // Set motor direction
// Generate step signal
digitalWrite(stepPin, HIGH);
delayMicroseconds(stepDelay); // Adjust speed here by changing the delay
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay);
}
}
Restart
Serial Input Speed Control
&
Forward Reverse Stepper Motor