RGB Led not fading properly with servos (solved)

I am attempting to fade an RGB Led across the color spectrum using the code below, however, when I run the code the led flashes green very briefly, then fades in blue, fades out, and then flashes red very briefly before turning off and restarting the cycle. When I instead use the code I've commented, it produces the same results but flipped (flash red, fade in and out blue, flash green).

I've confirmed that the ground pin (the long one) is correctly plugged in, and that the red, green, and blue pins are all plugged into ports 9, 10, and 11 respectively. I am using an Arduino uno r3, on which pins 9, 10, and 11 are all PWM, so that's not the problem. All 3 color pins have 220ohm resistors on them (I've also tried with 330ohm, same result), so that shouldn't be an issue either. I'm at a complete loss for what could be causing this strange behavior, and I've been unable to find any similar problem online.

const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;

void setup() {  
  setColourRgb(0,0,0);
}

void loop() {
  unsigned int rgbColour[3];
  
  rgbColour[0] = 255;
  rgbColour[1] = 0;
  rgbColour[2] = 0;
  
  for (int decColour = 0; decColour < 3; decColour += 1) {
    int incColour = decColour == 2 ? 0 : decColour + 1;
    
    for(int i = 0; i < 255; i += 1) {
      rgbColour[decColour] -= 1;
      rgbColour[incColour] += 1;
      
      setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]);
      delay(5);
    }
  }
  
  // using the code below produces the same results, just flipped
  // for( int i = 0; i <= 255; i++){
  //   analogWrite(redPin, i); // fade up 
  //   analogWrite(greenPin, 255 - i); // fade down
  //   analogWrite(bluePin, 0); // do nothing
  //   delay(5);
  // }
  // for( int i = 0; i <= 255; i++){
  //   analogWrite(redPin, 255 - i); // fade down
  //   analogWrite(greenPin, 0); // do nothing
  //   analogWrite(bluePin, i); // fade up 
  //   delay(5);
  // }
  //   for( int i = 0; i <= 255; i++){
  //   analogWrite(redPin, 0); // do nothing
  //   analogWrite(greenPin, i); // fade up
  //   analogWrite(bluePin, 255 - i); // fade down 
  //   delay(5);
  // }
}

void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

Nevermind, I've solved the problem. I was also using the Servo library with my code, and apparently it disables PWM on pins 9 and 10, so I just moved the LED to pins 3, 5, and 6.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.