Good solution for escape from loop/function needed

Hi guys,

I've made RGB lamp. It is working good, well at last as I wanted it to work :slight_smile:
However I'm not satisfied how I did exit from the loop/function I have inside my code.

Well, first piece of code I have:

// --= fadeUP function - brigthen LED from 0 to fVal  =-- //
void fadeUP(int led){
  if(RainbowActive){
    for(int fadeValue = 0 ; fadeValue <= fVal; fadeValue ++) { 
    analogWrite(led, fadeValue);         
    delay(30);                            
  }
  }
}

// --= fadeDOWN function - fade LED from fVal to 0  =-- //
void fadeDOWN(int led){
  if(RainbowActive){
  for(int fadeValue = fVal ; fadeValue >= 0; fadeValue --) { 
    analogWrite(led, fadeValue);         
    delay(30);                            
  }
  }
}  


// --= Interrupt routine  =-- //
void serialInterrupt()
{
  RainbowActive = false;
  firstRun = true;
}


// --= rainbow function - rainbow color effect  =-- //
void rainbow(){  
  if(firstRun){  
      analogWrite(RedLED, 0);
      analogWrite(GreenLED, 0);
      analogWrite(BlueLED, 0);
      fadeUP(RedLED);
    }
     fadeUP(GreenLED);
     fadeDOWN(RedLED);
     fadeUP(BlueLED);
     fadeDOWN(GreenLED);
     fadeUP(RedLED);
     fadeDOWN(BlueLED);
     firstRun = false;
}

What I do here is that I clear "RainbowActive" flag whenever interrupt occurs.
Then if that flag is cleared, I don't proceed function's code.
That works, but it might take a while before already started function will run till very end.

So my question is - how to make this better?
I don't expect ready solution - some thoughts which will lead me into correct direction would be more appreciate.

Here is my lamp project if anyone would be interested:

You need to move the test for RainbowActive inside the for loop.

  if(RainbowActive)
  {
     for(int fadeValue = 0 ; fadeValue <= fVal; fadeValue ++)
     { 
        analogWrite(led, fadeValue);         
        delay(30);                            
     }
  }

should be:

     for(int fadeValue = 0 ; fadeValue <= fVal && RainbowActive; fadeValue ++)
     { 
        analogWrite(led, fadeValue);         
        delay(30);                            
     }

This way, the flag will be checked on each iteration of the loop, rather than just once before the loop starts.

So simple !!

Thank you so much !