Well, look at you. You survived Module 2. You actually figured out how to wire up basic components without letting the magic smoke out, write C++ code without throwing your laptop out a window, read inputs, and output PWM signals. Iâm honestly a little impressed.
Now itâs time to prove it wasnât a fluke. Weâre going to cram all of those skills together into a single, somewhat-polished project: A customizable RGB Mood Light. Because nothing says âI understand electronicsâ quite like a glowing jar of colors.
Our final project: A beautiful, customizable mood light.
We are going to build a lamp that you can control manually.
An exposed LED is glaring to look at. To make it a true âmood lightâ, find a small frosted glass jar, a ping-pong ball with a hole cut in it, or fold a simple paper cube to place over the LED to diffuse the light.
We need to read the analog inputs (which give us 0-1023), mathematically scale those down to a PWM value (0-255), and apply that to the RGB pins.
// Define Pins
const int redLedPin = 9;
const int greenLedPin = 10;
const int blueLedPin = 11;
const int redPotPin = A0;
const int greenPotPin = A1;
const int bluePotPin = A2;
void setup() {
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);
Serial.begin(9600); // For debugging colors
}
void loop() {
// 1. Read the potentiometers (0 - 1023)
int redValue = analogRead(redPotPin);
int greenValue = analogRead(greenPotPin);
int blueValue = analogRead(bluePotPin);
// 2. Map the 10-bit analog read value to an 8-bit PWM value
// The map() function takes: (value, fromLow, fromHigh, toLow, toHigh)
int redPWM = map(redValue, 0, 1023, 0, 255);
int greenPWM = map(greenValue, 0, 1023, 0, 255);
int bluePWM = map(blueValue, 0, 1023, 0, 255);
// 3. Write the PWM values to the LED pins
analogWrite(redLedPin, redPWM);
analogWrite(greenLedPin, greenPWM);
analogWrite(blueLedPin, bluePWM);
// 4. Print the current mix to the Serial Monitor
Serial.print("R: ");
Serial.print(redPWM);
Serial.print("\tG: "); // \t prints a tab space
Serial.print(greenPWM);
Serial.print("\tB: ");
Serial.println(bluePWM);
delay(50); // Small delay for stability
}
map()The map() function is one of the most useful tools in Arduino. Because our analog knob reads up to 1023, but our PWM output only goes up to 255, we canât just pass the analog read directly into analogWrite(). The map() function proportionally scales the number down perfectly.
Turn your knobs and watch the colors mix inside your diffuser! Youâve successfully built an interactive physical computing device.
In Module 3, weâre going to ditch the knobs and start using sensors to make our Arduino react to the environment around it automatically.
[Ready for Module 3? Make sure your toolkit is stocked with a comprehensive Arduino Sensor Kit.]