Hardware Reference
In-Depth Information
Try It
/*
Serial RGB LED controller
Context: Arduino
Controls an RGB LED whose R, G and B legs are
connected to pins 11, 9, and 10, respectively.
*/
To start, you need to set up the
constants to hold the pin numbers.
You'll also need a variable to hold the
number of the current pin to be faded,
and one for the brightness.
// constants to hold the output pin numbers:
const int greenPin = 9;
const int bluePin = 10;
const int redPin = 11;
8
int currentPin = 0; // current pin to be faded
int brightness = 0; // current brightness level
The setup() method opens serial
communications and initializes the
LED pins as outputs.
8
void setup() {
// initiate serial communication:
Serial.begin(9600);
// initialize the LED pins as outputs:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// if there's any serial data in the buffer, read a byte:
if (Serial.available() > 0) {
int inByte = Serial.read();
In the main loop, everything
depends on whether you have
incoming serial bytes to read.
8
// respond to the values 'r', 'g', 'b', or '0' through '9'.
// you don't care about any other value:
if (inByte == 'r') {
currentPin = redPin;
}
if (inByte == 'g') {
currentPin = greenPin;
}
if (inByte == 'b') {
currentPin = bluePin;
}
If you do have incoming data, there
are only a few values you care
about. When you get one of the values
you want, use if statements to set the
pin number and brightness value.
8
Finally, set the current pin to the
current brightness level using the
analogWrite() command.
8
if (inByte >= '0' && inByte <= '9') {
// map the incoming byte value to the range of
// the analogRead() command:
brightness = map(inByte, '0', '9', 0, 255);
// set the current pin to the current brightness:
analogWrite(currentPin, brightness);
}
}
}
 
Search WWH ::




Custom Search