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();
}