I have a problem on how to keep my stepper motor moving when button is released. 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 = 13; // the number of the LED pin
const int dirPin = 8; // the number of the motor direction pin
const int stepPin = 9; // the number of the motor step 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(dirPin, OUTPUT); //YELLOW
pinMode(stepPin, OUTPUT); //ORANGE
digitalWrite(buttonPin, LOW);
digitalWrite(dirPin, HIGH);
digitalWrite(stepPin, HIGH);
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the state of the pushbutton
if (digitalRead(buttonPin) == LOW) { // If pushbutton is pressed, buttonState is HIGH:
digitalWrite(ledPin, HIGH);
digitalWrite(dirPin, LOW); // LOW=FORWARD DIRECTION
digitalWrite(stepPin, HIGH); // stepPin = MOTOR ON/OFF
delayMicroseconds(100);
digitalWrite(stepPin, LOW);
delayMicroseconds(100);
distance++;
if(distance > 21000){
distance = 0;
delay (3000);
reverse();
}
}
if (digitalRead(buttonPin) == HIGH){ // turn LED off:
digitalWrite(ledPin, LOW);
digitalWrite(dirPin, LOW); //LOW = FORWARD DIRECTION
digitalWrite(stepPin, LOW); //stepPin = MOTOR ON/OFF
delayMicroseconds(100);
digitalWrite(stepPin, LOW);
delayMicroseconds(100);
}
}
void reverse() {
digitalWrite(dirPin,HIGH); //HIGH = REVERSE DIRECTION
digitalWrite(stepPin,HIGH);
delayMicroseconds(100);
digitalWrite(stepPin,LOW);
delayMicroseconds(100);
distance++;
if(distance > 21000){
distance = 0;
delay(3000);
return;
}
reverse();
}
bool isMoving=true
and toggle that on each button press.