Color Mixer using an RGB LED

So I’ve written code to make a color mixer using an RGB LED. The red component of the RGB LED is connected to pin 6, blue to pin 5 and green to pin 3. Push-button switches S1, S2, and S3 are connected to pins 7, 8, and 9. Indicator LEDs are connected to pins 11, 12 and 13. S2 is used to change the color chosen in a cyclic fashion (from red to blue to green, and then back to red). S1, S3 are used to decrease, increase the intensity of the LED chosen. The indicator LEDs indicate the color chosen. The code is pretty straight-forward.

int color[3] = {6, 5, 3};
int choice[3] = {11, 12, 13};
int c = -1;
int i = 0;
int intensity[3] = {0, 0, 0};

void setup()
{
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop()
{
  if(!(digitalRead(8))) //S2 is pressed
  {
    while(!(digitalRead(8)));
    delay(30); //Debounce time
    
    if(c == 2)
      c = -1;
    c++; //Go to the next color when S2 is pressed.
    
    analogWrite(color[c], intensity[c]); //Turn on the RGB color component chosen
    
    for(i = 0; i <3; i++)
      digitalWrite(choice[i], 0); //Turn OFF all 3 indicator LEDs
      
    digitalWrite(choice[c], 1); //Turn ON the indicator LED for the color chosen
  }

  if(!(digitalRead(7))) //S1 is pressed
  {
    while(!(digitalRead(7)));
    delay(30);
    
    intensity[c] += 10; //Increase intensity corresponding to the currently chosen color
    
    if(intensity[c] > 255)
      intensity[c] = 255;
      
    analogWrite(color[c], intensity[c]);
  }
  
  if(!(digitalRead(9))) //S3 is pressed
  {
    while(!(digitalRead(9)));
    delay(30);
    
    intensity[c] -= 10; //Decrease intensity corresponding to the currently chosen color
    
    if(intensity[c] < 0)
      intensity[c] = 0;
      
    analogWrite(color[c], intensity[c]);
  }
}

The code works fine as it is. BUT, if the line “Serial.begin(9600);” is removed, the code doesn’t work at all. I get random outputs in that case. But I haven’t used serial communication at all in my program. Neither have I used pins 0 and 1. So why doesn’t my code work if I don’t specify the baud rate?

Yes it is strange that removing Serial.begin has any effect. I have not (yet) spotted any reason for this. But I did notice that you have not set pins 6, 5 & 3 as outputs. Perhaps analogWrite does this automatically (unlike digitalWrite).

Paul