source: arduino-1-6-7/trunk/fuentes/arduino-ide-amd64/examples/04.Communication/ReadASCIIString/ReadASCIIString.ino @ 4837

Last change on this file since 4837 was 4837, checked in by daduve, 2 years ago

Adding new version

File size: 1.8 KB
Line 
1/*
2  Reading a serial ASCII-encoded string.
3
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.
7
8 Circuit: Common-Cathode RGB LED wired like so:
9 * Red anode: digital pin 3
10 * Green anode: digital pin 5
11 * Blue anode: digital pin 6
12 * Cathode : GND
13
14 created 13 Apr 2012
15 by Tom Igoe
16 
17 modified 14 Mar 2016
18 by Arturo Guadalupi
19
20 This example code is in the public domain.
21 */
22
23// pins for the LEDs:
24const int redPin = 3;
25const int greenPin = 5;
26const int bluePin = 6;
27
28void setup() {
29  // initialize serial:
30  Serial.begin(9600);
31  // make the pins outputs:
32  pinMode(redPin, OUTPUT);
33  pinMode(greenPin, OUTPUT);
34  pinMode(bluePin, OUTPUT);
35
36}
37
38void loop() {
39  // if there's any serial available, read it:
40  while (Serial.available() > 0) {
41
42    // look for the next valid integer in the incoming serial stream:
43    int red = Serial.parseInt();
44    // do it again:
45    int green = Serial.parseInt();
46    // do it again:
47    int blue = Serial.parseInt();
48
49    // look for the newline. That's the end of your
50    // sentence:
51    if (Serial.read() == '\n') {
52      // constrain the values to 0 - 255 and invert
53      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
54      red = 255 - constrain(red, 0, 255);
55      green = 255 - constrain(green, 0, 255);
56      blue = 255 - constrain(blue, 0, 255);
57
58      // fade the red, green, and blue legs of the LED:
59      analogWrite(redPin, red);
60      analogWrite(greenPin, green);
61      analogWrite(bluePin, blue);
62
63      // print the three numbers in one string as hexadecimal:
64      Serial.print(red, HEX);
65      Serial.print(green, HEX);
66      Serial.println(blue, HEX);
67    }
68  }
69}
70
71
72
73
74
75
76
77
Note: See TracBrowser for help on using the repository browser.