r/ArduinoProjects • u/NA_18108 • Jan 11 '24
Motor doesnt reverse?
Hi Guys this is my current code, i have the motor running in 3 stages with the last stage the motor needs to run in reverese, im not sure what to change with my code to make this work, or if it is regarding my hardware. im using a cnc sheild v3 and the power is connected to a power supply with 12v.
This is the code:
const int StepX = 2;
bool initialRun = false;
bool mainRun = false;
bool reverseRun = false;
void setup() {
pinMode(StepX, OUTPUT);
}
void loop() {
// If the initial run is not completed
if (!initialRun) {
// Move the motor for a short distance
for (int i = 0; i < 200; i++) {
digitalWrite(StepX, HIGH);
delayMicroseconds(500);
digitalWrite(StepX, LOW);
delayMicroseconds(1000);
}
// Stop the motor (optional)
digitalWrite(StepX, LOW);
initialRun = true;
// Introduce a delay before starting the main run
delay(2000); // Adjust this delay as needed
}
// If the initial run is completed and the main run hasn't started
else if (!mainRun && initialRun) {
// Move the motor for a short distance in the opposite direction
for (int i = 0; i < 200; i++) {
digitalWrite(StepX, LOW); // Change direction to LOW for reverse
delayMicroseconds(500);
digitalWrite(StepX, HIGH); // Change direction to HIGH for reverse
delayMicroseconds(1000);
}
// Stop the motor (optional)
digitalWrite(StepX, LOW);
mainRun = true;
// Introduce a delay before starting the reverse run
delay(2000); // Adjust this delay as needed
}
// If the main run is completed and the reverse run hasn't started
else if (!reverseRun && mainRun) {
// Move the motor for a short distance in the opposite direction (reverse)
for (int i = 0; i < 200; i++) {
digitalWrite(StepX, LOW);
delayMicroseconds(500);
digitalWrite(StepX, HIGH);
delayMicroseconds(1000);
}
digitalWrite(StepX, LOW);
reverseRun = true;
}
}
This is the hardware:

2
u/QuackSparow Jan 11 '24
Ok first problem, you don’t wanna use “else if” it might cause problems for what it looks like you’re trying to do. Just use 3 if statements.
I’m gonna take a gamble this is your first time using a steppe motor controller like the 1 you have. Well you already did better than me remember to connect the enable pin. I think you just forgot to write to the direction pin. The direction pin does what it sounds like it does, changes the direction. You can look up online which pin on the Arduino mega corresponds to the X motor drive on the cnc shield but here’s your modified code
// If the main run is completed and the reverse run hasn’t started
if (!reverseRun && mainRun) { // Move the motor for a short distance
for (int i=0; i<200< i++) {
digitalWrite(Stepx, LOW);
delayMicroseconds(500);
digitalWrite(Stepx, HIGH);
delayMicroseconds(500); // I did change this delay from 1000 to 500
}
digitalWrite(StepX, LOW);
reverseRun = true;
}
} // :)