105Views4Replies

# Need help to make the stepper motor rotate in forward and reverse direction using limit switch? Answered

This is the code I used to forward the stepper for 360 degree,reverse the motor for 360 degree without using the switch. I need help to make the motor rotate in forward direction for 180 degree only after we click a limit switch and when we click the switch again,the motor have to rotate in reverse direction.

int pinStep = 3; // the number of the step pin
int pinDir = 2; //the number of direction pin
int oneRevStep = 1600;//one rev is 1600 steps
int speed = 2;//for 2 milliseconds delay

void setup(){
pinMode(pinStep,OUTPUT);
pinMode(pinDir,OUTPUT);
Serial.begin(9600);
}

void loop(){
move_forward(oneRevStep,speed);
delay(1000);
move_backward(oneRevStep,speed);
delay(1000);
}

void move_forward(int step,int speed)
{
int i;
digitalWrite(pinDir,LOW);
for(i=0;i<step;i++)
{
digitalWrite(pinStep,HIGH);
delay(speed);
digitalWrite(pinStep,LOW);
delay(speed);
}
digitalWrite(pinDir,LOW);
digitalWrite(pinStep,LOW);
}
void move_backward(int step,int speed)
{
int i;
digitalWrite(pinDir,HIGH);
for (i=0;i<step;i++)
{
digitalWrite(pinStep,HIGH);
delay(speed);
digitalWrite(pinStep,LOW);
delay(speed);
}
digitalWrite(pinDir,LOW);
digitalWrite(pinStep,LOW);
}

Tags:

## 4 Replies

iceng (author)2016-05-01

Stepper motors don't know where they are at power up, and the limit sw becomes the orientation point for regular operation.

Further a stepper can slip steps if accelerated too fast, making the the limit sw a handy reference that should be Czecked, I was born in Czechoslovakia, at regular intervals.

Downunder35m (author)2016-05-01

It makes absolutely no sense to have a limit switch for stopping and starting the motor.
Once it is stopped it needs to move to free the switch - which in no mormal configuration seems usable.
Either you took the wrong turn for the project or you don't understand what limit switches are used for.
So it would help to get all the details involved to give proper advise.

rickharris (author)2016-05-01

It is a stepper motor you make it do x steps to go 180 deg and that is what it will do no need for the limit unless there is more to this than you have told us.

All you need is code. the stepper is by it's nature very accurate and repeatable.

steveastrouk (author)2016-04-30

So start by making it move 180 degrees. And add a switch to your hardware setup.