abort for-loop at any time

hey dudes,

i have a for-loop fading out an LED within about 2 seconds. This loops starts, if a pin gets a Signal and ends, when the loop has finished - of course. But i need a script, which allows to end the loop immediately, when signal is lost.

Has anybody a solution?

break; will exit the for loop when it is called. So if you monitor the signal and it suddenly stops, you can call break; and it will exit the loop.

It does the same thing for while loops too.

But i need a script, which allows to end the loop immediately, when signal is lost.

You could look at the blink without delay example. Instead of blinking, you define what the next fade value is.

Depending on your definition of “immediately”, you could roll your own delay that involves checking for the signal, and ending the for loop when the signal goes away.

bool keepGoing = true;
for(byte i=0; i<255; i++)
{
    analogWrite(redPin, i);
    unsigned long started = millis();
    while(millis() - started < fadeInterval)
    {
        if(digitalRead(signalPin) != HIGH)
        {
            keepGoing = false;
            break;
        }
    }
}

(deleted)

 if (buttonState_run == HIGH) {

          for(int fadeValue = 30 ; fadeValue <= 255; fadeValue +=5) {
            if (buttonState_run == LOW) {break;}
            analogWrite(ledPin_run, fadeValue);        
            delay(30);                            
          }

          for(int fadeValue = 255 ; fadeValue >= 30; fadeValue -=5) {
            if (buttonState_run == LOW) {break;}
            analogWrite(ledPin_run, fadeValue);        
            delay(30);      
          }
     }

MC runs fading until the end without breaking when signal is lost :frowning:
Did I make a mistake?

Your not reading the signal pin in the for loop, your reading what it previously was and not what it currently is. Try to digitally read the pin while in the for loop.

Did I make a mistake?

Yes.

HazardsMind:
break; will exit the for loop when it is called. So if you monitor the signal and it suddenly stops, you can call break; and it will exit the loop.

It does the same thing for while loops too.

break ; exits the innermost enclosing loop or switch statement.

@HazardsMind

Thank you. It works now.

Another way to do it is to make the loop variable go out of range.

for (i =0;i<=100;i++){
if (you want to exit the loop) i = 101;}

It won’t break out immediately, only at the end of the for loop (closing curly bracket), but before the next itteration.