# 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;
}
}
``````

``````  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

Glad to hear it

Have fun!

A more compact way:

``````    analogWrite(LED,255-abs(255-counter));