2 LEDs fading in and out at the same time?

I have a general question in order to code correctly

Given the following case:

  • There are two LEDs to be driven separately
  • The LEDs "fade in" for 0,5sec and "fade out" for 2 sec
  • Each lamp is activated by a pushbutton

Theoretically the following usage could happen:

  • LED 1 is activated
  • LED 1 will be deactivated
  • WHILE the LED1 "fade out" occurs, lamp 2 will be activated

I know how to code a fade out/ fade in feature. But how to connect it in that way that a fade in and fade out happens at the same time? [smiley=huh.gif]

There are couple of pins that can be PWM driven. You can control them separately and in this way achieving independent dimming of both leds.

In the loop(), set the first LED, then the second, based on time passed. As in, get the time the first loop around, set a boolean that says you already got the time to true, and then you divide the time passed by the total time to get the percentage of power for each LED.

If both LEDS fade at the exact same time, just find LED1's percentage. LED2 = 1.0 - LED1percent

Aenas,
my idea was somthing like that. This is pseudocode neglecting fade out feature...

if (switch1 > 100 )
{lightsonvariable1 = 1 }

if (switch2 > 100 )
{lightsonvariable2 = 1 }


if (lightsonvariable1 ==1 )
{   for (int i=0; i <= 255; i++){
      analogWrite(PWMpin1, i);
      delay(10);  } 
   
   
if (lightsonvariable2 ==1 )
{  for (int i=0; i <= 255; i++){
      analogWrite(PWMpin2, i);
      delay(10);}

And here I am struggeling, because the switch 2 is not recognized before the "for" loop has finished. So both fade in features cannot be used with a time dely of e.g. 0.2 seconds.

You have to put what you have in the for loops into a state machine, with a "time for next update on fade" as a variable you check each time through the loop.

Use the buttons to trigger a fade so you code would check if the time for next fade was due AND if in fact a fade cycle was in train. Then you would remove all the delays() in the code.

Just dropping in to propose this:

if (lightsonvariable1 ==1 || lightsonvariable2 ==1) {
  for (int i=0; i <= 255; i++) {
    if (lightsonvariable1 ==1 ) { analogWrite(PWMpin1, i); }
    if (lightsonvariable2 ==1 ) { analogWrite(PWMpin2, i); }
    delay(10);
  }
}

:slight_smile: