Saturday, 17 December 2016

Arduino rgb led code

In this post I will share a small sketch by which you can control a RGB led and make what ever colour you want.
Ad

How many colour can you make with this sketch?
Actually it's all up to you how many colours you want to make, but in this sketch 5 colours has been set.
  • Red
  • Green
  • Blue
  • Yellow
  • Aqua
Functions:
After wiring up the led and uploading the sketch you can use these commands to cotrol the led.
on = On
off = Off
g = Green
r = Red
b = Blue
y = Yellow
a = Aqua

The Sketch

int redPin = 4;
int greenPin = 5;
int bluePin = 6;

#define COMMON_ANODE
void setup() {
// initialize serial communication at 9600 bits per second:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
 Serial.begin(9600);
}

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);



String str;

void r(){
  setColor(255, 0, 0); // red
  Serial.println("The red led is on now");
}

void g(){
setColor(0, 255, 0); // green 
  Serial.println("The green led is on now");
}

void b(){
 setColor(0, 0, 255); // blue
   Serial.println("The blue led is on now");
}

void y(){
 setColor(255, 255, 0);// yellow
   Serial.println("The yellow led is on now");
}

void a(){
setColor(0, 255, 255);// aqua 
  Serial.println("The aqua led is on now");
}

void on(){
setColor(255, 255, 255);// on
  Serial.println("The light is on now");
}

void off(){
setColor(0, 0, 0);// off
  Serial.println("The light is off now");
}


void loop() {
 
  if(Serial.available())
{
str = Serial.readStringUntil('\n');

if(str == "g"){
g();
  }

if(str == "r"){
r();
  }

if(str == "b"){
b();
  }

if(str == "y"){
y();
  }

if(str == "a"){
a();
  }

if(str == "off"){
off();
  }

if(str == "on"){
on();
  }
 }
}

How do you make these colours?
Well, it's simple just by controlling and mixing these three (Red, Green and Blue) colours you can make as many colours you want.

For example by turning on red and green you make yellow colour. setColor(255, 255, 0);// yellow
and  by mixing green and blue you make a Aqua colour. setColor(0, 255, 255);// aqua 

Where can I find the RGB codes?
Just Google it you will find plenty of them make sure you don't get html code that's different than these.
Note: You might use resistors for led, I didn't use it because it was not making colours properly for me.

Ad



2 comments:

  1. The problem with traditional grow lights with such high usage are many fold and speak to comparative strengths of LED's in general. Grow Tent

    ReplyDelete
  2. We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. Best led grow lights

    ReplyDelete