Arduino Lesson 3. RGB LEDs(https://learn.adafruit.com/adafruit-arduino-lesson-3-rgb-leds)

Overview

In this lesson, you will learn how to use a RGB (Red Green Blue) LED with an Arduino.
You will use the analogWrite function of Arduino to control the color of the LED.
learn_arduino_project_3_on_breadboard.jpg
At first glance, RGB (Red, Green, Blue) LEDs look just like regular LEDs, however, inside the usual LED package, there are actually three LEDs, one red, one green and yes, one blue. By controlling the brightness of each of the individual LEDs you can mix pretty much any color you want.

We mix colors just like you would mix audio with a 'mixing board' or paint on a palette - by adjusting the brightness of each of the three LEDs. The hard way to do this would  be to use different value resistors (or variable resistors) as we played with in lesson 2. That's a lot of work! Fortunately for us, the Arduino has an analogWrite function that you can use with pins marked with a ~ to output a variable amount of power to the appropriate LEDs.




Code

  1. /*
  2. Adafruit Arduino - Lesson 3. RGB LED
  3. */
  4.  
  5. int redPin = 11;
  6. int greenPin = 10;
  7. int bluePin = 9;
  8.  
  9. //uncomment this line if using a Common Anode LED
  10. //#define COMMON_ANODE
  11.  
  12. void setup()
  13. {
  14. pinMode(redPin, OUTPUT);
  15. pinMode(greenPin, OUTPUT);
  16. pinMode(bluePin, OUTPUT);
  17. }
  18.  
  19. void loop()
  20. {
  21. setColor(255, 0, 0); // red
  22. delay(1000);
  23. setColor(0, 255, 0); // green
  24. delay(1000);
  25. setColor(0, 0, 255); // blue
  26. delay(1000);
  27. setColor(255, 255, 0); // yellow
  28. delay(1000);
  29. setColor(80, 0, 80); // purple
  30. delay(1000);
  31. setColor(0, 255, 255); // aqua
  32. delay(1000);
  33. }
  34.  
  35. void setColor(int red, int green, int blue)
  36. {
  37. #ifdef COMMON_ANODE
  38. red = 255 - red;
  39. green = 255 - green;
  40. blue = 255 - blue;
  41. #endif
  42. analogWrite(redPin, red);
  43. analogWrite(greenPin, green);
  44. analogWrite(bluePin, blue);
  45. }

ความคิดเห็น