#define stepPin 2 // Define digital pin for STEP
#define dirPin 3 // Define digital pin for DIR
#define enablePin 4 // Define digital pin for ENABLE
#define buttonForwardPin 5 // Define digital pin for forward button
#define buttonReversePin 6 // Define digital pin for reverse button
bool isClockwise = true; // Variable to track the direction
void setup() {
Serial.begin(9600);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(buttonForwardPin, INPUT_PULLUP); // Use internal pull-up resistors
pinMode(buttonReversePin, INPUT_PULLUP);
digitalWrite(enablePin, LOW); // Enable the motor driver
}
void loop() {
// Check the state of the forward button
if (digitalRead(buttonForwardPin) == LOW) {
Serial.println("Forward button pressed. Rotating motor clockwise...");
isClockwise = true;
}
// Check the state of the reverse button
else if (digitalRead(buttonReversePin) == LOW) {
Serial.println("Reverse button pressed. Rotating motor counterclockwise...");
isClockwise = false;
}
// Rotate motor continuously based on the direction
if (isClockwise) {
rotateClockwise();
} else {
rotateCounterclockwise();
}
}
void rotateClockwise() {
digitalWrite(dirPin, HIGH); // Set direction (HIGH for clockwise)
digitalWrite(stepPin, HIGH);
delayMicroseconds(1000); // Adjust delay as needed for your motor
digitalWrite(stepPin, LOW);
delayMicroseconds(1000); // Adjust delay as needed for your motor
}
void rotateCounterclockwise() {
digitalWrite(dirPin, LOW); // Set direction (LOW for counterclockwise)
digitalWrite(stepPin, HIGH);
delayMicroseconds(1000); // Adjust delay as needed for your motor
digitalWrite(stepPin, LOW);
delayMicroseconds(1000); // Adjust delay as needed for your motor
}