Help with a button and RGB LED setup. Arduino Uno.

Hi,

I recently got an Arduino Uno and after going through some tutorials, decided to try my hand at making a small project. Basically, I want to press a push button and for every time I push the button, an RGB LED slightly changes it’s color. I tried to mish mash some code together from the tutorial I’ve been doing but I have’t had any success. I have attached my code but it seems the pictures of my setup are too large. Thanks for any tips or help!

const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;
const int buttonPin = 2;


void setup()
{

  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
  pinMode(buttonPin, INPUT);
}


void loop()
{
  int x = 0;
  int buttonState;
  buttonState = digitalRead(buttonPin);
   if (buttonState == LOW); {
    x = x + 10;
  }
showRGB(x);
}

void showRGB(int color)
{
  int redIntensity;
  int greenIntensity;
  int blueIntensity;

  if (color <= 255)
  {
    redIntensity = 255 - color;
    greenIntensity = color;
    blueIntensity = 0;
  }
  else if (color <= 511)
  {
    redIntensity = 0;
    greenIntensity = 255 - (color - 256);
    blueIntensity = (color - 256);
  }
  else 
  {
    redIntensity = (color - 512);
    greenIntensity = 0;
    blueIntensity = 255 - (color - 512);
  }

  analogWrite(RED_PIN, redIntensity);
  analogWrite(BLUE_PIN, blueIntensity);
  analogWrite(GREEN_PIN, greenIntensity);
}

I think I see a couple of issues.

You are setting x to zero every time through the loop. When you push the button, it changes to 10, but as soon as you release the button it just returns to zero and stays at zero.

If you move the initialization of x out of the loop (into setup) it will fix that. But, you'll probably still want some way of resetting to zero so it doesn't just count-up forever.

Does showRGB() work? Have you tried just "forcing" different x values to see how the colors change?

Hi,

Another thing you need to do is wait for the button to be released before you increase x again. Otherwise even a short button press will increase x by several hundred.

Declare an int variable at the top of the sketch called something like "lastButtonState". Use this to detect when the button state has changed, not just when it is low.

Buttons bounce. Like dropping a ball, the ball will bounce a few times before it comes to rest. Same thing happens when you press a switch, but much faster. If you put a delay(50) in your sketch when it detects a button press, that will prevent the sketch from increasing x for each bounce.

Your showRGB() function can accept a colour value between 0 and 767. After you increase x, check if it has gone to 768 or over. If it has, subtract 768 from it.

Paul

Hi.

pictures of my setup are too large

Load your image into windows Paint, Resize it to 1000 pixels across. Then save it as jpg.

Tom.... :)