Step motor with button

Hello.

I'm trying to use a button to make my step motor work but it was suppost only work while i'm pressing the button but it's always working and when i press the button it stop. What did i do wrong?

This is the code

#include <Stepper.h>
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int stepsPerRevolution = 500;
Stepper myStepper(stepsPerRevolution, 8,10,9,11); 
 

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {

 // initialize the pushbutton pin as an input:
 pinMode(buttonPin, INPUT);
 myStepper.setSpeed(60);
}

void loop() {
 // read the state of the pushbutton value:
 buttonState = digitalRead(buttonPin);

 // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
 if (buttonState == HIGH)
{
myStepper.step(-513); [code]
// delay(2000);
}       
 }

Hi,
Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

What are you driving the stepper with?
What is your stepper spec/data, can you post a link.

How are you powering your project?

Thanks.. Tom... :slight_smile:

Do you have an external resistor wired with your switch? You are not using the internal pullup resistor, so you MUST have an external one. Is it wired as a pullup or pulldown resistor?

I'm only using a step motor, the arduino and the button plug in arduino

and the button plug in arduino

What the heck is that supposed to mean?

It means that the button has 2 wires and one is at pin 2 and the other is connected at GND

bunogenrinho:
It means that the button has 2 wires and one is at pin 2 and the other is connected at GND

So, no external resistor? You need to add one, or use the internal pullup resistor.

I saw some youtube videos and they don't use it and still work

bunogenrinho:
I'm only using a step motor, the arduino and the button plug in arduino

bunogenrinho:
It means that the button has 2 wires and one is at pin 2 and the other is connected at GND

Then your code is wrong, since when the button is pressed digitalRead() will return LOW, not HIGH.

Just declare the pin mode thus:

 pinMode(buttonPin, INPUT_PULLUP);

and change your button press logic to:

 // check if the pushbutton is pressed. If it is, the buttonState is LOW:
 if (! buttonState)  // use negation operator, much less cumbersome

Using the internal pullups like this is possible only if the button switches to ground.

It's working :smiley: Thank you guys, but a special thanks to MarkT ^^