Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * RGB.ino
- * Program to make the color of an RGB LED attached to an Arduino change based on the reading of a potentiometer.
- * Shows how to use RGB LEDs, potentiometers, and switch statements
- * 123D Circuits demo: https://123d.circuits.io/circuits/1543748-the-unnamed-circuit/
- * Codebender: https://codebender.cc/sketch:230656
- * Diagram of color changes: http://i.imgur.com/jDrOQUy.png
- * Schematic: http://i.imgur.com/hTR5oGr.png
- */
- int redpin = 11; // setting pin #s for the colors
- int greenpin = 10;
- int bluepin = 9;
- int r, g, b = 0; // these will be used for color values; init to 0 for now
- int value;
- void setup() { // run once, when the sketch starts
- pinMode(redpin, OUTPUT); // set pinmodes
- pinMode(greenpin, OUTPUT);
- pinMode(bluepin, OUTPUT);
- Serial.begin(9600); // set up Serial library at 9600 bps
- }
- void loop() { // run over and over again
- value = analogRead(A0); //find potentiometer value
- Serial.println(value);
- switch ((value-value%170)/170){ //figures out how many times 170 goes into the value to the nearest whole number, then switches on this number
- //* this part of the code is for a common anode LED; remove the first slash to switch to common cathode
- case 0: // increases red
- r = 255-(value)*3/2; // because 0<value<170, 0<value for color<255 (it is a common anode so the values are reversed)
- g = 255;
- b = 255; // green and blue are not lit up
- break;
- case 1: // increases green
- r = 0;
- g = 255-(value-170)*3/2;
- b = 255;
- break;
- case 2: // increases blue
- r = 0;
- g = 0;
- b = 255-(value-340)*3/2;
- break;
- case 3: // decreases value for red
- r = (value-510)*3/2;
- g = 0;
- b = 0;
- break;
- case 4: // decreases value for green
- r = 255;
- g = (value-680)*3/2;
- b = 0;
- break;
- case 5: // decreases value for blue
- r = 255;
- g = 255;
- b = (value-850)*3/2;
- break;
- default: // since 170 * 6 is 1020, this will usually happen from 1020 to 1024, and it also works fine as a default if something goes wrong
- r = 255; // all colors are turned off
- g = 255;
- b = 255;
- break;
- /*/ this part of the code is for a common cathode LED
- case 0: // increases red
- r = (value)*3/2;
- g = 0;
- b = 0;
- break;
- case 1: // increases green
- r = 255;
- g = (value-170)*3/2;
- b = 0;
- break;
- case 2: // increases blue
- r = 255;
- g = 255;
- b = (value-340)*3/2;
- break;
- case 3: // decreases red
- r = 255-(value-510)*3/2;
- g = 255;
- b = 255;
- break;
- case 4: // decreases greeen
- r = 0;
- g = 255-(value-680)*3/2;
- b = 255;
- break;
- case 5: //decreases blue
- r = 0;
- g = 0;
- b = 255-(value-850)*3/2;
- break;
- default: //all colors are off
- r = 0;
- g = 0;
- b = 0;
- break;
- //*/
- }
- analogWrite(redpin, r); // setting colors to the led
- analogWrite(greenpin, g);
- analogWrite(bluepin, b);
- delay(10); //brief delay
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement