Go Down

### Topic: Limit switch control of stepper motor direction (Read 6720 times)previous topic - next topic

#### hosaba

##### Feb 23, 2013, 12:31 am
Hi,
I am trying to control a stepper using the stepper.h library on the Arduino UNO.
The only additional thing is the control of direction of rotation of the stepper with a limit switch.
For either of the two conditions (HIGH and LOW) with the if statement in the code, the stepper motor works as intended.
However, when the two conditions are put together, only the HIGH condition is recognized.
Does anybody have any suggestions.
The code is
Code: [Select]
`#include <Stepper.h> //stepper libraryconst int stepback = 2; //motorpinconst int stepforw = 3; //motorpinconst int Switch1= 4;  // pin from limit switchint one_rotation=6400; //number of steps required for easydriver at 1/8 step//to complete one revolution. int n=1;int Steps=8; //change the number of steps to achieve resolution and speedint rotation=one_rotation/Steps;int j = 0;int k;int Distance = n*rotation; //number of revolution times step in a revolutionint RPM = 20;Stepper mystepper= Stepper (rotation, stepforw, stepback);void setup(){  Serial.begin(9600);  pinMode(Switch1, INPUT);  //pin from limit switch  digitalWrite(Switch1, LOW); //limit switch pin; not necessary  digitalWrite(stepback,LOW); // stepper motor pin1  digitalWrite(stepforw,LOW); // stepper motor pin2  analogReference(DEFAULT);  mystepper.setSpeed(RPM);  // set the speed of the stepper}void loop(){      if (digitalRead(Switch1)==LOW) //limit switch is off    {    mystepper.step(Steps);    //steps in forward direction       }        if (digitalRead(Switch1)==HIGH) //limit switch is on        {          mystepper.step(-Steps);   //reverse direction                }}`

#### MarkT

#1
##### Feb 23, 2013, 01:25 am
You have only one limit switch?  How is that supposed to work?

Also your code is stateless, you need to have the current direction as a variable (which has state).

Currently it will go till it hits the switch and then oscillate as the switch goes on and off in rapid succession.

You need each limit switch to trigger a change in state in the correct direction - not one switch trying to
control both directions.
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]

#2