Using Two Momentary Buttons to Move a Stepper CW or CCW

Hello, having a little bit of trouble with my code here. I'd like the stepper motor to not be turning at all if neither momentary button is pressed. But once the first button is pressed, the motor will turn CW. Once released, it will stop. The same goes for the second button just CCW.

Currently, the buttons do what they're supposed to but the motor is constantly turning when neither button is pressed.

/* sketch 1 
turn on a LED when the button is pressed
turn it off when the button is not pressed (or released)
*/
#define dirPin 2
#define stepPin 3
#define buttonCW 8
#define buttonCCW 9

void setup() {
  pinMode(buttonCW, INPUT); //set the button pin as INPUT
  pinMode(dirPin, OUTPUT); //set the LED pin as OUTPUT
  pinMode(buttonCCW, INPUT); //set the button pin as INPUT
  pinMode(stepPin, OUTPUT); //set the LED pin as OUTPUT
}

void loop()
{
  if(digitalRead(buttonCCW))
  digitalWrite(dirPin, HIGH);
else if(digitalRead(buttonCW))
  digitalWrite(dirPin, LOW);
else
{
  // move
}
  // These four lines result in 1 step:
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

Any help is appreciated.

Do you not use a library for controlling it?

Robin2's simple stepper program may be of interest.

No I don't, I figured for just doing two buttons it might not be necessary. I'm going based off this tutorial piece.

Perfect!

You set the direction, CW or CCW according to the buttons. Then You go along stepping disregarding the state of the buttons. That's the error. Insert an if statement checking for any of the two buttons being pressed. If any button is pressed, do the stepping. Else, do nothing.

void loop()
.
.
.

// These four lines result in 1 step:
if (digitalRead(buttonCCW) || digitalRead(buttonCW))
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
}
}

If you get a signal when no button is pressed it might be the floating state of the inputs with pinMode set to INPUT. You should either connect a 4.7k resistor between +Vcc and the pin OR use INPUT_PULLUP and wire each switch between the pin and ground. This way you will get rid of noise triggering your floating inputs.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.