Arduino code to run stepper motor clockwise and anticlockwise in a loop

Dear all,

I am new to the field of Arduino. I have to run a stepper motor in clockwise for some degrees (say 180°) and anticlockwise for some degrees (say 180°).

I have followed the tutorial How to Control Stepper motor with Arduino - YouTube and built exactly the same set up using 12V 4-wire stepper motor, a stepper motor driver and Arduino controller. The wiring diagram is attached with this question.

PUL+ : 5V
DIR+ : 5V
DIR- : D8
PUL- : D9

The Arduino code to run in clockwise direction is like this:

void setup() {
// put your setup code here, to run once:

pinMode(8,OUTPUT);
pinMode(9,OUTPUT);

}

void loop() {
// put your main code here, to run repeatedly:

//digitalWrite(8,HIGH); //for reverse direction
digitalWrite(9,LOW);
delay(2);
digitalWrite(9,HIGH);
delay(2);
}

This code works perfectly fine. There is also provision of reverse the direction and run the motor in anticlockwise by un-commenting the said line.

I have learnt how to run a motor in bi-directions by changing the codes, but now, I have to run the motor in clockwise for some degrees (lets say half turn) and anticlockwise for some degrees (lets say half turn) continuously in a loop.

What changes can I make in the code. I am really poor in coding, It would be great if someone can help me here.

Your post was MOVED to its current location as it is more suitable.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

You need a loop like :
for(int step = 0; step < **number of steps for 180 degrees** ; step++)

then

{
digitalWrite(9,LOW);
delay(2);
digitalWrite(9,HIGH);
delay(2);
}

then reverse

digitalWrite(9, !digitalRead(9));

The !digitalRead(9) reads the current pin state and turns it on of off and off if on.

1 Like

@lirilsilvi, your topic has been moved to a more suitable location on the forum. At the moment that you can upload code, Installation and Troubleshooting is the wrong section.

When posting code, please use code tags. Edit your post, select all code and click </>; next save your post. It makes is easier to read, the forum software will not mangle it and it's easier to copy.

Thanks for the help. It worked.

Here is the code

//Servo servo1;
const int stepPin = 9;
const int dirPin = 8;
void setup() {
// put your setup code here, to run once:

pinMode(8,OUTPUT);
pinMode(9,OUTPUT);

}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(dirPin,LOW);

for(int x = 0; x<200; x++)
{
digitalWrite(stepPin,LOW);
delayMicroseconds(5000);
digitalWrite(stepPin,HIGH);
delayMicroseconds(5000);
}
delay(1000);
digitalWrite(dirPin,HIGH);

for(int x = 0; x<200; x++)
{
digitalWrite(stepPin,LOW);
delayMicroseconds(5000);
digitalWrite(stepPin,HIGH);
delayMicroseconds(5000);
}
delay(1000);
}