Rainbow Colour Cycle
Part of the Outputs section of Coddy's Arduino journey. Lesson 8 of 24.
Every colour takes three digitalWrite() lines. A sequence of six colours would take 18 of them, and it is easy to mix up which line is which.
A function makes it short. setColor() takes one value for each colour and writes all three pins:
void setColor(int red, int green, int blue) {
digitalWrite(redPin, red);
digitalWrite(greenPin, green);
digitalWrite(bluePin, blue);
}Now each colour is one line, and its three values read like a recipe:
setColor(HIGH, HIGH, LOW); // yellow
delay(500);HIGH and LOW are the numbers 1 and 0, so they fit in an int parameter. Keep the parameters in the same order as you pass them: red, green, blue.
Challenge
EasyWrite setColor() and use it to show a rainbow, half a second per colour, again and again:
- red
- yellow
- green
- cyan
- blue
- magenta
Press Run, then Check.
Try it yourself
const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void setColor(int red, int green, int blue) {
// write each value to its pin
}
void loop() {
setColor(HIGH, LOW, LOW); // red
delay(500);
// then yellow, green, cyan, blue and magenta
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
Practice on your own: Arduino playground