1

I found a code that turns on different RGB colors but I would like it to blink rapidly one color once called. I dont want to use void loop function to make this possible. My RGB is a cathode. Any help?

int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);  
}

void loop()
{
    for (int j = 0; j <= 10; j++) //LED simply stays on. No blinking occuring
     {
      setColor(255, 0, 0);
      delay(100);
      setColor(0, 0, 0);
        }
}

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);  
}
  • You need another delay as the last line in the for loop. Currently it is turning it off and then immediately turning it on at the top of the loop. – mwwalk Nov 13 '16 at 0:16
  • give another delay after setColor(0,0,0). – dhimaspw Dec 13 '16 at 1:57
1

Simply do this:

int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  blinkLed();
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void blinkLed()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 0, 0);  // off
  delay(1000);
}

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.

NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.

EDIT

FULL CODE ADDED

  • Is there a way to do this without using loop function? Say with a while or for loop? I'm actually using this function within a code. – flyer3110 Nov 12 '16 at 22:29
  • Yes you can, simply insert it in whatever loop you want – Dat Ha Nov 12 '16 at 22:29
  • I tried but the LED stays on – flyer3110 Nov 12 '16 at 22:33
  • I've included the FULL code. If it doesn't work, describe in detail what happens. – Dat Ha Nov 12 '16 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.