A4988 and a Nema 17 stepper motor control via switches

hi all,

i've got a Uno, A4988 and a Nema 17 stepper motor. I can get the stepper motor working on it's own but i'm wanting to add switches to turn it x amount one way then the same the other.

now i can get the switch working and it will continiously turn the motor when pressed. Is there any suggestions on how i can get it to turn it x amount in either direction?

Existing code?

this is what i had so far

const int stepPin = 9;
const int dirPin = 8;
int BUTTON = 4;
int LED = 13;

void setup() {
pinMode(9,OUTPUT);
pinMode(8,OUTPUT);
pinMode(BUTTON,INPUT);
pinMode(LED,OUTPUT);
}

void loop() {

if(digitalRead(BUTTON) == HIGH)
{
for(int x = 0; x < 100; x++)
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
}else
{
digitalWrite(stepPin,LOW);
}

springs:
now i can get the switch working and it will continiously turn the motor when pressed. Is there any suggestions on how i can get it to turn it x amount in either direction?

You need to view your program as two almost completely separate parts. One part reads a button and saves its value. The other part controls the motor based on the saved value.

Something like this pseudo code

void loop() {
  readButton();
  moveMotor();
}

void readButton() {
  if (buttonState == HIGH) { // assumes LOW when pressed
                                        // only read button if there is nothing happening
    buttonState = digitalRead(buttonPin);
  }
}

void moveMotor() {
  if (buttonState == LOW) {
    // code to move motor the required number of steps
    buttonState = HIGH;  // when motor is finished allow further reads of the button pin
  }
}

…R
Stepper Motor Basics
Simple Stepper Code