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