How to stop a for loop and hold value

I’m play with this code i figured it would get to 255 and the if statement would hold it there but the out come is not what I think it just starts all over

void fade(){
int fadeValue = 0; //initial led brightness (variable)
for (int fadeValue = 0 ; fadeValue <= 255 ; fadeValue += 1)
{
analogWrite(ledPin, fadeValue);
delay(100);
if (fadeValue == 255){
  analogWrite(ledPin, fadeValue);
}
}
}

I tried this which should be better but the led just jumps the fully on.

void fade(){
   int fadeValue = 0; //initial led brightness (variable)
   for (int fadeValue = 0 ; fadeValue <= 255 ; fadeValue += 1)
   analogWrite(ledPin, fadeValue);
   if (fadeValue == 255);
   delay(100);

}

If fade() is called from inside loop() of course, it is going to start over again.

You would need to add something like while(1) in the if statement to make it stop.

Otherwise, it just executes the code in the statement and just continues on.

Fade is only run on button press but I was trying to figure how to hold it when I gets 255 and adding the if statement it just turns full on

This loop:

   for (int fadeValue = 0 ; fadeValue <= 255 ; fadeValue += 1)
   analogWrite(ledPin, fadeValue);

will, in probably less than 100 microseconds, increment fadeValue from 0 to 255 and then exit with fadeValue=256.

You will never see the effect of the intermediate steps.

You're aware that you actually have two different variables called fadeValue with different scope?

can you just change

for (int fadeValue = 0 ; fadeValue <= 255 ; fadeValue += 1)

to

for (int baz = 0 ; fadeValue <= 255 ; fadeValue += 1)

This give a nice fade but I still can’t figure how to stop it at 255 and go on to the next step.

void fade(){
for (int fadeValue = 0 ; fadeValue <= 255 ; fadeValue += 1)

{
analogWrite(ledPin, fadeValue);
delay(100);

}

Change “<=” to “<”

void fade(){
for (int fadeValue = 0 ; fadeValue < 255 ; fadeValue += 1)
  {
   analogWrite(ledPin, fadeValue);
   delay(100);
   }

That didn’t change the fade it’s still the same but If use a if statement I get a error I guess a do while statement would be better.