Using fade in a button counter loop

I'm trying to fade an led in and out when a pushbuton counter reaches 3. my counter works great but i realized i cannot use a for statement because it hard for the code to jump back out on a button press. so my teacher told me to use an if statement. he suggested i didn't need two counter but i wasn't sure ho to do it that way. anyways i have counter1 counting up to 255 then when it hits 255 it switches to the other counter to start counting down. what its doing is just outputting 5 on counter1 and -5 on counter 2.

before setup
int counter1 = 0;
int counter2 = 0;

if (ButtonCount == 3){
  if (counter1 <= 255) {
  counter1 =counter1 + 5;
  analogWrite (LED, counter1);
  }
  if (counter1 == 255) {
  counter2 = counter1;
  }
  if (counter2 >= 0) { 
  counter2 =counter2 - 5;
  analogWrite (LED, counter2);
  }
  if (counter2 == 0) {
  counter1 = counter2;
  }
}

How about:

  if (counter1 < 255) {
    counter1 =counter1 + 5;
    analogWrite (LED, counter1);
  }
  if (counter1 == 255) {
    counter2 = counter1;
    counter1 = 256; //stop counter1
  }
  if (counter2 > 0) {
    counter2 =counter2 - 5;
    analogWrite (LED, counter2);
  }
  if (counter2 == 0) {
    counter1 = counter2;
    counter2 = -1; //stop counter2
  }

initialize counter2 to -1

wow thanks alot. tht works perfect :slight_smile:

Glad to hear it :slight_smile:

Have fun!

A more compact way:

(start with int counter=0)

    analogWrite(LED,255-abs(255-counter));
    counter+=5;

(stop when counter>=511)

Just feel like I have to say: although the math trickery is cool I would think that the OP should use the counter logic and ifs for his assignment. Chances are that some part of his assessment criteria is to show that he understands control structures. This is purely speculation from my part.