Hardware Reference
In-Depth Information
To control this RGB LED, you send three separate 8-bit values (0-255) to set
the brightness of each LED color. For example, to set all the colors to full bright-
ness, you send “255,255,255” . This presents a few challenges:
You need to differentiate between numbers and commas.
You need to turn this sequence of characters into integers that you can
pass to analogWrite() functions.
You need to be able to handle the fact that values could be one, two, or
three digits.
Thankfully, the Arduino IDE implements a very handy function for identifying
and extracting integers: Serial.parseInt() . Each call to this function waits until
a non-numeric value enters the serial buffer, and converts the previous digits
into an integer. The first two values are read when the commas are detected,
and the last value is read when the newline is detected.
To test this function for yourself, load the program shown in Listing 6-5 on
to your Arduino.
Listing 6-5: RGB LED Control via Serial—list_control.ino
//Sending Multiple Variables at Once
//Define LED pins
const int RED =11;
const int GREEN =10;
const int BLUE =9;
//Variables for RGB levels
int rval = 0;
int gval = 0;
int bval = 0;
void setup()
{
Serial.begin(9600); //Serial Port at 9600 baud
//Set pins as outputs
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
}
void loop()
{
//Keep working as long as data is in the buffer
while (Serial.available() > 0)
Search WWH ::




Custom Search