2015年11月8日 星期日

Arduino 3: LED - - RGB

共陰極 RGB LED

使用random()來隨機產生數值:


  1. #define LEDR 9
  2. #define LEDG 10
  3. #define LEDB 11

  4. void setup() {               
  5.   pinMode(LEDR, OUTPUT);
  6.   pinMode(LEDG, OUTPUT);
  7.   pinMode(LEDB, OUTPUT);
  8. }

  9. int r = 0;
  10. int g = 0;
  11. int b = 0;
  12. void loop() {
  13.   r = random(0, 255);
  14.   g = random(0, 255);
  15.   b = random(0, 255);
  16.   analogWrite(LEDR, r);
  17.   analogWrite(LEDG, g);
  18.   analogWrite(LEDB, b);
  19.   delay(1000);
  20.  }

改用[可變電阻]改變不同的R、G、B數值:

  1. #define LEDR 9
  2. #define LEDG 10
  3. #define LEDB 11

  4. void setup() {               
  5.   pinMode(LEDR, OUTPUT);
  6.   pinMode(LEDG, OUTPUT);
  7.   pinMode(LEDB, OUTPUT);

  8.   Serial.begin(9600);
  9. }

  10. int r = 0;
  11. int g = 0;
  12. int b = 0;

  13. void loop() {
  14.   int rREAD=analogRead(0);
  15.   int gREAD=analogRead(1);
  16.   int bREAD=analogRead(2);
  17.      //r = random(0, 255);
  18.      //g = random(0, 255);
  19.      //b = random(0, 255);
  20.   r = map(rREAD, 0,1023, 0,255);  
  21.   g = map(gREAD, 0,1023, 0,255);
  22.   b = map(bREAD, 0,1023, 0,255); 
  23.   
  24. Serial.println(r);
  25. Serial.println(g);
  26. Serial.println(b);
  27.   
  28.    analogWrite(LEDR, r);
  29.    analogWrite(LEDG, g);
  30.    analogWrite(LEDB, b);
  31.  delay(100);
  32. }

Attiny85

  1. // This program is in the public domain.
  2. // This sketch waits for an IR pulse from a remote control
  3. // and then randomly changes the color of an RGB LED

  4. int ledPinRED = 2;    // LED on digital pin 2
  5. int ledPinGREEN = 1;  // LED on digital pin 1
  6. int ledPinBLUE = 4;   // LED on  digital pin 0
  7. int inPin = 0;               // the input pin for the IR phototransistor
  8. int randRED = 0;
  9. int randGREEN = 0;
  10. int randBLUE = 0;

  11. void setup() {
  12.   pinMode(inPin, INPUT);    // declare IR phototransistor as input
  13. }

  14. void loop(){
  15.   while(digitalRead(inPin) != LOW) {};  // read input value
  16.   
  17.     randRED = random(255); // picking a random number
  18.     randGREEN = random(255); // between 1 and 255
  19.     randBLUE = random(255);
  20.    
  21.     analogWrite(ledPinRED, randRED);        
  22.     analogWrite(ledPinGREEN, randGREEN);        
  23.     analogWrite(ledPinBLUE, randBLUE);        
  24.     delay(100);  // de-bounces the input so it does not zoom
  25.                  // through a zillion colors with every button click   
  26.   }

沒有留言:

張貼留言