Problem with Simple Fading Between Two LEDs

Hello Everyone,

I am new to Arduino development and learning things quickly.

I modified the Fade example to fade between two LEDs.

const int yellowPin = 9;    // Red LED to PWM pin 9
const int redPin = 11;  // Yellow LED to PWM pin 11
// Cathod pins on both LEDs are connected to GND

void setup()
{ 
  // nothing happens in setup 
} 

void loop()
{ 
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5)
  { 
    analogWrite(redPin, fadeValue);
    analogWrite(yellowPin, (255 - fadeValue));
    
    delay(30);                        
  }
  
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5)
  { 
    analogWrite(redPin, fadeValue);
    analogWrite(yellowPin, (255 - fadeValue));
    
    delay(30);    
  } 
}

When I run the sketch, both fully bright and then they take turns, each fading out and then back in before the other fades out and back in. My original intention was to have one fade in while the other fades out.

What have I done wrong?

Zoltan

I pasted your code into a blank sketch, and connected 2 LEDs, 2 resistors, and a wire to ground. I uploaded the sketch. One LED starts bright, while the other is off. The one that is off gradually rams up, while the other ramps down.

I'd say that the sketch was working correctly.

Have you used resistors in your circuit? What value? How are they connected?

A schematic would help, sounds like it could be a hardware issue.

I wonder why I'm not getting the same result. I tried adding resistors between the Anodes and the PWM pins and I still have the same effect. Red fades down and back up while yellow stays bright and then yellow fades down and back up while red stays bright. I've tried other PWM channels and nothing seems to work.

Here is essentially what I have. The resistor color codes are not true.

I'm using 330 Ohm resistors that came with the Arduino Starter Kit from SparkFun.com.

2 small issues noticed:

Schematic shows you using 9 and 10, but code uses 9 and 11.

Also, you need to set the pins to outputs in the setup section.

void setup()
{
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
}

Also, you need to set the pins to outputs in the setup section.

That is not correct, analogWrite will set the pinMode inside the function call.

Never knew that actually. Should have checked that long time ago.

For anyone else following, here are the function notes:

        // We need to make sure the PWM output is enabled for those pins
      // that support it, as we turn it off when digitally reading or
      // writing with them.  Also, make sure the pin is in output mode
      // for consistenty with Wiring, which doesn't require a pinMode
      // call for the analog output pins.
        pinMode(pin, OUTPUT);

Do you have any other LEDs to try out? I think the same setup with 2 fresh LEDs to compare notes with might help troubleshoot.