| 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 through 220 ohm resistor |
| 10 |
- green anode: digital pin 5 through 220 ohm resistor |
| 11 |
- blue anode: digital pin 6 through 220 ohm resistor |
| 12 |
- cathode: GND |
| 13 |
|
| 14 |
created 13 Apr 2012 |
| 15 |
by Tom Igoe |
| 16 |
modified 14 Mar 2016 |
| 17 |
by Arturo Guadalupi |
| 18 |
|
| 19 |
This example code is in the public domain. |
| 20 |
|
| 21 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/ReadASCIIString |
| 22 |
*/ |
| 23 |
|
| 24 |
// pins for the LEDs: |
| 25 |
const int redPin = 3; |
| 26 |
const int greenPin = 5; |
| 27 |
const int bluePin = 6; |
| 28 |
|
| 29 |
void setup() { |
| 30 |
// initialize serial: |
| 31 |
Serial.begin(9600); |
| 32 |
// make the pins outputs: |
| 33 |
pinMode(redPin, OUTPUT); |
| 34 |
pinMode(greenPin, OUTPUT); |
| 35 |
pinMode(bluePin, OUTPUT); |
| 36 |
|
| 37 |
} |
| 38 |
|
| 39 |
void loop() { |
| 40 |
// if there's any serial available, read it: |
| 41 |
while (Serial.available() > 0) { |
| 42 |
|
| 43 |
// look for the next valid integer in the incoming serial stream: |
| 44 |
int red = Serial.parseInt(); |
| 45 |
// do it again: |
| 46 |
int green = Serial.parseInt(); |
| 47 |
// do it again: |
| 48 |
int blue = Serial.parseInt(); |
| 49 |
|
| 50 |
// look for the newline. That's the end of your 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 |
} |