Toggle Stepper Motor 180*

I had a servo motor toggle that was working when you pushed the button it rotated 180*, then if you pushed it again it would rotate 180* back the other direction.

I took this working servo motor code and modified it to control a stepper motor instead, and there is a problem in my loop where its just running the stepper motor non stop as soon as it boots up.

  1. Can you see where I made a mistake? Here is my code:
  2. I've tried experimenting with getting the stepper motor to go the opposite way (ex: motor.step(-800)), however the stepper motor always seems to rotate clockwise.
 #include <Stepper.h>

int button = 2; //button pin, connect to ground to move servo
int press = 0;
boolean toggle = false;

Stepper motor(200, 8,9,10,11);            

void setup() {
  pinMode(button, INPUT); //arduino monitor pin state
   Serial.begin(9600);
}

void loop() {
  
  int Speed = analogRead(A0);
  int RPM = map(Speed, 0, 1023, 0, 200);
  
  press = digitalRead(button);
  if (press == LOW)
  {
    if(toggle)
    {
      
    motor.step(800);
    motor.setSpeed(RPM);
    toggle = !toggle;
    }
    else
    {
    motor.step(-800);
    motor.setSpeed(RPM);
    toggle = !toggle;
    }
  }
  Serial.println(RPM);
}

For my setup:

I think you need to use the PULLUP feature on the button pin so that it is high unless the button is pressed. Pins are low by default.

pinMode(button, INPUT_PULLUP); //arduino monitor pin state

...R

Thanks Robin, I will try that tonight

  1. Any idea why the stepper motor isnt turning counterclockwise when given a negative value (ex: -800)?

  2. Also I have a question about is the code has this line, but nothing is plugged into the Analog pin holes in the Arduino (A0, A1, etc).

int Speed = analogRead(A0);

I haven't used the stepper library myself (I have just written my own code) so I don't know what is the correct way to tell it to go backwards. Is there a direction function?

I don't understand why you have code with analogRead(A0) if you don't have a potentiometer connected to A0 to set the speed? Maybe you are using code that you got somewhere else.

I think if you use analogRead() on an unconnected pin you will get random values. If you haven't got anything connected to A0 then I would change that line to

int Speed = 1023; // try different numbers between 0 and 1023

...R