r/ArduinoProjects • • 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:

1 Upvotes

11 comments sorted by

View all comments

Show parent comments

3

u/NA_18108 Jan 11 '24

Bro years? I got 3 weeks 😅

2

u/QuackSparow Jan 11 '24

Nice, you’re not doing to shabby for 3 weeks

1

u/NA_18108 Jan 11 '24

thaks mate, ive been using these website, reddit and youtube and some ChatGPT (suprisingly very helpful especially breaking things down and giving considerations), i was suprised how much I can do with the interent. These are the resources roughly so far, and i started with tinker cad too.

https://www.youtube.com/watch?v=TMK_fLgpESQ&t=901s

https://howtomechatronics.com/tutorials/arduino/stepper-motors-and-arduino-the-ultimate-guide/

https://forum.arduino.cc/t/cnc-shield-with-o-a-speed-control-potentiometer/689100/5

This too has helped so far as ive just tried to add a potentiometer to the second phase.

3

u/QuackSparow Jan 11 '24

Yeah, those are good. I like to watch DroneBotWorkshop on YouTube, he has a bunch of good videos on basically everything including the A4988 which you’re using