]> git.piffa.net Git - sketchbook_andrea/blob - RGB_LED/rgb_3_ReadASCIIString/rgb_3_ReadASCIIString.ino
rgb
[sketchbook_andrea] / RGB_LED / rgb_3_ReadASCIIString / rgb_3_ReadASCIIString.ino
1 /*
2   Reading a serial ASCII-encoded string.
3   
4   Beware: set monitor to NL NewLine only
5  
6  This sketch demonstrates the Serial parseInt() function.
7  It looks for an ASCII string of comma-separated values.
8  It parses them into ints, and uses those to fade an RGB LED.
9  
10  Circuit: Common-anode RGB LED wired like so:
11  * Red cathode: digital pin 3
12  * Green cathode: digital pin 5
13  * blue cathode: digital pin 6
14  * anode: +5V
15  
16  Once you have programmed the Arduino, open your Serial minitor. 
17  Make sure you have chosen to send a newline character when sending a message. 
18  Enter values between 0-255 for the lights in the following format : 
19  Red,Green,Blue. 
20
21  
22  Once you have sent the values to the Arduino, 
23  the attached LED will turn the color you specified, 
24  and you will receive the HEX values in the serial monitor. 
25  
26  created 13 Apr 2012
27  by Tom Igoe
28  
29  This example code is in the public domain.
30
31
32
33   Schema: http://lab.piffa.net/schemi/rgb.jpg
34
35  */
36
37 // pins for the LEDs:
38 const int redPin = 11;
39 const int greenPin = 10;
40 const int bluePin = 9;
41
42 void setup() {
43   // initialize serial:
44   Serial.begin(9600);
45   // make the pins outputs:
46   pinMode(redPin, OUTPUT);
47   pinMode(greenPin, OUTPUT);
48   pinMode(bluePin, OUTPUT);
49
50 }
51
52 void loop() {
53   // if there's any serial available, read it:
54   while (Serial.available() > 0) {
55
56     // look for the next valid integer in the incoming serial stream:
57     int red = Serial.parseInt();
58     // do it again:
59     int green = Serial.parseInt();
60     // do it again:
61     int blue = Serial.parseInt();
62
63     // look for the newline. That's the end of your
64     // sentence:
65     if (Serial.read() == '\n') {
66       // constrain the values to 0 - 255 and invert
67       // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
68       red = 255 - constrain(red, 0, 255);
69       green = 255 - constrain(green, 0, 255);
70       blue = 255 - constrain(blue, 0, 255);
71
72       // fade the red, green, and blue legs of the LED:
73       analogWrite(redPin, red);
74       analogWrite(greenPin, green);
75       analogWrite(bluePin, blue);
76
77       // print the three numbers in one string as hexadecimal:
78       Serial.print(red, HEX);
79       Serial.print(green, HEX);
80       Serial.println(blue, HEX);
81     }
82   }
83 }