0

I have written the following code for RGB LED:-

const int RED =11;
const int GREEN = 10;
const int BLUE= 9;
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN,OUTPUT);
  pinMode(BLUE,OUTPUT);
}

void loop() {
  analogWrite(RED,0);
  analogWrite(GREEN,255);
  analogWrite(BLUE,0);
  delay(1000);
}

Now according to my understanding if I run the above code then only pin named GREEN i.e. 10th pin will give me current not 9, 11th pin. But when I upload the code and run it I see that 9 and 11 pin are giving me current not 10th pin as it is supposed to. Is there a problem in my code? I have checked my circuits are correct. To check current I took jumper wire that was connected to one of my colour and tried inserting it's other end at pins(9, 10 or 11) of Arduino board. If there is current bulb will glow. For above code the bulb was glowing when I inserted the wire at 9 and 11th pin.

  • 1
    Can we check that your circuit is correct too? – Majenko May 20 at 18:26
  • 1
    How do you know, that the other pins output a voltage? And what type of RGB LED do you have? Common anode or common cathode? – chrisl May 20 at 18:28
  • What do you mean by “give me current”. You are controlling voltage, not current. – Edgar Bonet May 20 at 19:59
  • @chrisl I took jumper wire that was connected to one of my colour and tried inserting it's other end at pins. If there is current bulb will glow. It's common anode – Bhavya Budhia May 20 at 20:46
2

A common anode RGB LED can be sketched in a schematic like this:

schematic

simulate this circuit – Schematic created using CircuitLab

The positive voltage has to be applied to the top, for all the LEDs together. To light the LEDs up, you have to sink the current on the other end, meaning providing ground level at the bottom of that schematic at the corresponding pins. The current will then flow from your 5V pin, through the LEDs into the Arduinos pin.

That means, that analogWrite(pin, 0) will turn the LED on that pin ON and analogWrite(pin, 255) will turn the LED OFF. The logic is inverted here, because the Arduinos output pin is on the other side of the LED.

So your circuit and code work perfectly, you just didn't expect the inverted logic.


Note: The pins of the Arduino can only source/draw a certain amount of current (20mA continuously, 40mA at maximum) without getting damaged. A single, not too strong RGB LED should be OK, but as soon, as you want to drive more LEDs, you should consider using a driver circuit (for example simple transistors). That way the output pins don't have to provide the LEDs current, but only the current to control the transistor.

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.