How to stop a fading loop / led & proximity sensor

Hi all,

I have been working on a sketch for some time now but it seems that I will need your help in order to achieve my goal.

I have been using a proximity sensor and a led strip. My aim is to get data from the sensor in order to turn the led strip on and off, so that when the distance is less than 40cm the led will be switched off while for distance greater than 40cm, the led will be on. I have managed to do so with the code I am attaching. However,my aim is to create a fading effect for the turning on/off state. At the moment I am using a 'for' loop which makes the led strip to fade, but I need somehow to control the loop as I do not want it to run continuesly. I just want to see the fading effect once (when I move from >40 to <40 and if I stay at a distance <40 the led should be switched off). With my code, the loop runs without a stop and if I stay at a sidtance smaller than 40cm, the led is turned on/fading out and again turned on/fading out..

I have tried the 'break'command and a variety of other modifications but didn't succeeded so far...
Any help would be great!

thanks

////////////////////////////////////////////////////////
//SENSOR
#define trigPin 6
#define echoPin 7 
// RGB
#define REDPIN 9
#define GREENPIN 10
#define BLUEPIN 11
 
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

////////////////////////////////////////////////////////
void setup() {
  
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}
 
////////////////////////////////////////////////////////
void loop() {

//SENSOR  
 long duration, distance;
  digitalWrite(trigPin, LOW);  
  delayMicroseconds(10); 
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); 
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  
//RGB
  if (distance > 40) {
      setColor(255, 255, 255);  // white
  }
  else{
    for(int fadeValue = 0; fadeValue <= 255; fadeValue ++){
    setColor(fadeValue, fadeValue, fadeValue);  // fade
    delay(2); 
    
  } 
  }
  
}

////////////////////////////////////////////////////////
void setColor(int red, int green, int blue)
{
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);  
}
////////////////////////////////////////////////////////

Add a variable to stop the action:

byte done = false;    // make this global

//RGB
  if (distance > 40)
  {
      setColor(255, 255, 255);  // white
      done = true
  }
  
  if (done == true  && distance < 40) )
  {
    for(int fadeValue = 0; fadeValue <= 255; fadeValue ++)
    {
    setColor(fadeValue, fadeValue, fadeValue);  // fade
    delay(2); 
    }
    done = false;
  }

Hi LarryD,

Thank you for the reply!! I ll give it a try tmrw!