KEEP MOTOR MOVING

Hello, I have a problem on how to keep my stepper motor moving even when button is not pressed. It should only stop moving if I press the button again.

For now, stepper motor is only moving IF the button is constantly pressed.

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int ledPin =  49;      // the number of the LED pin

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

void setup() {

  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(8, OUTPUT); //YELLOW
  pinMode(9, OUTPUT); //OREN
  
  digitalWrite(buttonPin, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
}

void loop() {

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

  if (digitalRead(buttonPin) == LOW && buttonState == 0) {    // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   
   digitalWrite(ledPin, HIGH);
   digitalWrite(8, LOW);                 //LOW=FORWARD DIRECTION
   digitalWrite(9, HIGH);               //9 = MOTOR ON/OFF
   delayMicroseconds(100);
   digitalWrite(9, LOW);
   delayMicroseconds(100);
   distance++;

   if(distance > 21000){
    distance = 0;
    delay (3000);
    reverse();
    }
   
  } 
  
  if (digitalRead(buttonPin) == HIGH && buttonState == 1){
    // turn LED off:
   digitalWrite(ledPin, LOW);
   digitalWrite(8, LOW); //LOW=FORWARD DIRECTION
   digitalWrite(9, LOW); //9 = MOTOR ON/OFF
   delayMicroseconds(100);
   digitalWrite(9, LOW);
   delayMicroseconds(100);
  }
}

void reverse(){

  digitalWrite(8,HIGH);

  digitalWrite(9,HIGH);
  delayMicroseconds(100);
  digitalWrite(9,LOW);
  delayMicroseconds(100);
  distance++;

   if(distance > 21000){
    distance = 0;
    delay (3000);
   return;
   }

   reverse();
   
  }

Have a look at the state change detection tutorial. It shows how to detect the switch transitions, as opposed to switch states.

hai, I've referred to the code. it seems like it only works for the led but not for the motor. thanks for the help btw !

sarahisml:
hai, I've referred to the code. it seems like it only works for the led but not for the motor. thanks for the help btw !

You need to post the program in which you tried to apply the state-change code to your stepper motor problem. And tell us exactly what happens when you run the program.

...R
Stepper Motor Basics
Simple Stepper Code