Q:

Stopping and starting loops in arduino

I need a motor to cycle forward, then backward when the user pushes a once. the problem is, the arduino will run in loops after it is presses and wont stop.
How can i make it only cycle through once each time the button is pushed?
Ive tried exit(0), stop_it, etc, but those just exit the loop instead of starting back up when the button is pressed another time.
const int pwm_pin = 9;
const int dir_1a_pin = 8;
const int dir_2a_pin = 7;
int buttonPin = 2;
boolean on=false;
int buttonState = 0;

void setup() {
pinMode(buttonPin, INPUT);
pinMode(pwm_pin, OUTPUT);
pinMode(dir_1a_pin, OUTPUT);
pinMode(dir_2a_pin, OUTPUT);

}

void loop() {

buttonState = digitalRead(buttonPin);

if (buttonState == HIGH){
  if (on==true){
    on=false;
  } else{
    on=true;
  }
 }
if(on == true){ 
digitalWrite(dir_1a_pin, HIGH);
digitalWrite(dir_2a_pin, LOW);
analogWrite(pwm_pin, 255);
delay (8000);

digitalWrite(dir_1a_pin, LOW);
digitalWrite(dir_2a_pin, HIGH);
analogWrite(pwm_pin, 255);
delay (12000);

}
}

A:

You are making the logic too much complicated. Just read the button state in your loop and if it was HIGH do your motorcycle job. The next time loop runs as you haven't pressed the button it would become LOW and won't go into if statement.
const int pwm_pin = 9;
const int dir_1a_pin = 8;
const int dir_2a_pin = 7;
int buttonPin = 2;

void MotorCycle()
{
    digitalWrite(dir_1a_pin, HIGH);
    digitalWrite(dir_2a_pin, LOW);
    analogWrite(pwm_pin, 255);
    delay(8000);

    digitalWrite(dir_1a_pin, LOW);
    digitalWrite(dir_2a_pin, HIGH);
    analogWrite(pwm_pin, 255);
    delay(12000);
}

void setup()
{
    pinMode(buttonPin, INPUT);
    pinMode(pwm_pin, OUTPUT);
    pinMode(dir_1a_pin, OUTPUT);
    pinMode(dir_2a_pin, OUTPUT);
}

void loop()
{
    // if button pressed
    if (digitalRead(buttonPin) == HIGH)
    {
        MotorCycle();
    }
}

