2 Reading a serial ASCII-encoded string.
4 This sketch demonstrates the Serial parseInt() function.
5 It looks for an ASCII string of comma-separated values.
6 It parses them into ints, and uses those to fade an RGB LED.
8 Circuit: Common-anode RGB LED wired like so:
9 * Red cathode: digital pin 3
10 * Green cathode: digital pin 5
11 * blue cathode: digital pin 6
17 This example code is in the public domain.
22 const int greenPin = 5;
23 const int bluePin = 6;
28 // make the pins outputs:
29 pinMode(redPin, OUTPUT);
30 pinMode(greenPin, OUTPUT);
31 pinMode(bluePin, OUTPUT);
36 // if there's any serial available, read it:
37 while (Serial.available() > 0) {
39 // look for the next valid integer in the incoming serial stream:
40 int red = Serial.parseInt();
42 int green = Serial.parseInt();
44 int blue = Serial.parseInt();
46 // look for the newline. That's the end of your
48 if (Serial.read() == '\n') {
49 // constrain the values to 0 - 255 and invert
50 // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
51 red = 255 - constrain(red, 0, 255);
52 green = 255 - constrain(green, 0, 255);
53 blue = 255 - constrain(blue, 0, 255);
55 // fade the red, green, and blue legs of the LED:
56 analogWrite(redPin, red);
57 analogWrite(greenPin, green);
58 analogWrite(bluePin, blue);
60 // print the three numbers in one string as hexadecimal:
61 Serial.print(red, HEX);
62 Serial.print(green, HEX);
63 Serial.println(blue, HEX);