Skip to content

Commit 77d902a

Browse files
author
Tom Igoe
committed
Added ReadASCIIString example to Communication examples
1 parent a0ae9c8 commit 77d902a

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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-anode RGB LED wired like so:
9+
* Red cathode: digital pin 3
10+
* Green cathode: digital pin 5
11+
* blue cathode: digital pin 6
12+
* anode: +5V
13+
14+
created 13 Apr 2012
15+
by Tom Igoe
16+
17+
This example code is in the public domain.
18+
*/
19+
20+
// pins for the LEDs:
21+
const int redPin = 3;
22+
const int greenPin = 5;
23+
const int bluePin = 6;
24+
25+
void setup() {
26+
// initialize serial:
27+
Serial.begin(9600);
28+
// make the pins outputs:
29+
pinMode(redPin, OUTPUT);
30+
pinMode(greenPin, OUTPUT);
31+
pinMode(bluePin, OUTPUT);
32+
33+
}
34+
35+
void loop() {
36+
// if there's any serial available, read it:
37+
while (Serial.available() > 0) {
38+
39+
// look for the next valid integer in the incoming serial stream:
40+
int red = Serial.parseInt();
41+
// do it again:
42+
int green = Serial.parseInt();
43+
// do it again:
44+
int blue = Serial.parseInt();
45+
46+
// look for the newline. That's the end of your
47+
// sentence:
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);
54+
55+
// fade the red, green, and blue legs of the LED:
56+
analogWrite(redPin, red);
57+
analogWrite(greenPin, green);
58+
analogWrite(bluePin, blue);
59+
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);
64+
}
65+
}
66+
}
67+
68+
69+
70+
71+
72+
73+
74+

0 commit comments

Comments
 (0)