1
votes

I'm trying to exit the void loop() after an if statement within the loop returns true. In other words, if the condition for the if statement is met, I want it to only run once and stop fully. This is used to control a DC motor with a potentiometer. So, as the potentiometer is HIGH, the dc motor should run for 1 second and stop fully and as the potentiometer is LOW the motor should run backward and stop fully. I'm having trouble exiting the loop.

Below is my code:

const int potIn = A0;
const int actIn = A1;
const int outA = 3;
const int outB = 11;

int potInput = 0;
int actInput = 0;
int outputValue = 0;
int potAnalog = 0;

void setup() {
    // put your setup code here, to run once:


    pinMode(potIn, INPUT);
    pinMode(actIn, INPUT);
    pinMode(outA, OUTPUT);
    pinMode(outB, OUTPUT);

}

void loop() {
    //  put your main code here, to run repeatedly:
    potInput = digitalRead(potIn);
    actInput = analogRead(actIn);
    potAnalog = analogRead(potIn);


    if (potInput == HIGH){
        digitalWrite(outA, LOW);
        digitalWrite(outB, HIGH);
        delay(1000);
        digitalWrite(outA, LOW);
        digitalWrite(outB, LOW);
        delay(1000);
        for (int i = 0; i < 10; i++) {
            if(i == 1)
                break;
        }
    }


    if (potInput == LOW){
        digitalWrite(outA, HIGH);
        digitalWrite(outB, LOW);
        delay(1000);
    }
}
3
Unclear - which if statement within the loop? Which loop? The function named loop or a loop within loop?Weather Vane
The function named loop. The first if statement within void loop ()Hussein Al-Hashimi
for (int i = 0; i < 10; i++) { if(i == 1) break; } does not seem to serve any useful purpose. The break exits the for loop. If you return from the void loop it will be called again.Weather Vane
It's a function. If you want to 'leave' it, just 'return;'Martin James
@Weather Vane how do I use the break command to execute that if statement then?Hussein Al-Hashimi

3 Answers

1
votes

adding the statement exit(0); at the end, works for me!

-1
votes

delete the void loop and use int main() with while(true) inside....you can now exit from the while whenever you want

-1
votes

you can write your code into an int main() function instead of void loop(). void loop() is simply a function where the statement is: while (true) { } so you have this solution:

Delete void loop and write a while (flag==true){ } where you have to write your code (your void loop code) inside the braces and simply set flag to false when you have to exit from the loop.