2 Reading a serial ASCII-encoded string.
4 Beware: set monitor to NL NewLine only
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.
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
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 :
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.
29 This example code is in the public domain.
33 Schema: http://lab.piffa.net/schemi/rgb.jpg
38 const int redPin = 11;
39 const int greenPin = 10;
40 const int bluePin = 9;
45 // make the pins outputs:
46 pinMode(redPin, OUTPUT);
47 pinMode(greenPin, OUTPUT);
48 pinMode(bluePin, OUTPUT);
53 // if there's any serial available, read it:
54 while (Serial.available() > 0) {
56 // look for the next valid integer in the incoming serial stream:
57 int red = Serial.parseInt();
59 int green = Serial.parseInt();
61 int blue = Serial.parseInt();
63 // look for the newline. That's the end of your
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);
72 // fade the red, green, and blue legs of the LED:
73 analogWrite(redPin, red);
74 analogWrite(greenPin, green);
75 analogWrite(bluePin, blue);
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);