The following information is a single lesson in a larger project. Find more great projects here.

Return to Previous Lesson: Setting Up the Circuit

Lesson Overview:

Now we'll write our color mixing code!

Step 1: Introduction

In this lesson you will learn how to write the code that connects the set of three light sensors to the RGB LED. As you change the amount of light falling on each sensor, the RGB LED will change its color to match.

Our version of the Color Mixing Lamp circuit is already in the Workplane. It should look a lot like the circuit that you created in the previous lesson!

  1. Continue to the next step.

Step 2: Useful Constants

Set up constants for the pins you’re using for input and output, so you can keep track of which sensor pairs with each color on the LED. Use constant integer for the datatype.

A constant integer (const int) is a value that you cannot change later in the program.

  1. Copy the code into the Code Editor: const int greenLEDPin = 9; const int blueLEDPin = 10; const int redLEDPin = 11; const int redSensorPin = A0; const int greenSensorPin = A1; const int blueSensorPin = A2;
  2. The datatype (int) will be highlighted purple or tan when you copy it into the Code Editor or Arduino IDE.
  3. Pins 9-11 are the digital output pins that will control the red, green, and blue LEDs Pins A0-A2 are the analog input pins that will interpret how much colored light is hitting each photoresistor.
  4. Continue to the next step.

Step 3: Variables to Store Light Intensity

Add variables for the incoming sensor values and for the output values you’ll be using to fade the LED. You can use the int (integer) datatype for all of these variables.

  1. Copy the code into the Code Editor: int redValue = 0; int greenValue = 0; int blueValue = 0; int redSensorValue = 0; int greenSensorValue = 0; int blueSensorValue = 0;
  2. Variables redValue, etc, will store the intensity of light for setting RGB LED brightness by PWM. Variables redSensorValue, etc, will store the light intensity hitting the sensors.
  3. Continue to the next step.

Step 4: Digital Pins and Serial Port

In the setup() function you will begin serial communication at 9600 bps (bits per second). Like in the previous project, you will use the serial monitor to visualize sensor values.

Next, define the LED pins as outputs with the pinMode() function.

The entire setup() function is shown below.

  1. Copy the code into the Code Editor: void setup(){ Serial.begin(9600); pinMode(greenLEDPin, OUTPUT); pinMode(redLEDPin, OUTPUT); pinMode(blueLEDPin, OUTPUT); }
  2. Continue to the next step.
  3. Stuck? HINT: Don't forget to include the {curly bracket} to end the setup() function.

Step 5: Reading Sensor Values

In the loop() function, read the sensor values on A0, A1, and A2 with analogRead() and store the values in the appropriate variables.

You will put a small delay() between each analogRead() because the ADC (analog to digital converter) takes a millisecond to do its work! The argument in the delay() function is in units of milliseconds.

  1. Copy the code into the Code Editor: void loop(){ redSensorValue = analogRead(redSensorPin); delay(5); greenSensorValue = analogRead(greenSensorPin); delay(5); blueSensorValue = analogRead(blueSensorPin);
  2. Analog sensor readings always take on values between 0 and 1023. Later, you will convert this to a more useful value.
  3. Continue to the next step.

Step 6: Report Sensor Readings to the Computer

Next print out the sensor values on one line. The “\t” is the equivalent of pressing the “tab” key on the keyboard.

  1. Copy the code into the Code Editor: Serial.print("Raw SensorValues \t Red: "); Serial.print(redSensorValue); Serial.print("\t Green: "); Serial.print(greenSensorValue); Serial.print("\t Blue: "); Serial.println(blueSensorValue);
  2. In the serial monitor, your data will look like this: Raw SensorValues Red: 1000 Green: 560 Blue: 400
  3. The last line in this section of code is a Serial.println() function. This means that a new line is started in the serial monitor after this code runs.
  4. Continue to the next step.

Step 7: Convert Sensor Readings

The function to change the LED’s brightness via PWM is called analogWrite(). analogWrite() needs two arguments: the pin to write to, and a value between 0-255.

This second number represents the duty cycle the Arduino will output on the specified pin:

A value of 255 will set the pin HIGH 100% of the time, making the attached LED as bright as it can be.

A value of 127 will set the pin HIGH for 50% of the period, making the LED dimmer.

A value of 0 would set the pin LOW 100% of the time, turning the LED off.

To convert the sensor reading from a value between 0-1023 to a value between 0-255 for analogWrite(), simply divide the sensor readings by 4.

  1. Copy the code into the Code Editor: //convert sensor values to PWM duty cycle # redValue = redSensorValue/4; blueValue = blueSensorValue/4; greenValue = greenSensorValue/4;

  2. Continue to the next step.

Step 8: Report the Calculated LED Light Levels

Next, print out the new mapped values on their own line.

  1. Copy the code into the Code Editor: //report PWM values to serial port Serial.print("Mapped SensorValues \t Red: "); Serial.print(redValue); Serial.print("\t Blue: "); Serial.print(blueValue); Serial.print("\t Green: "); Serial.println(greenValue);
  2. Along with the previous information sent through the serial port, the information in the serial monitor will look like this (for example): Raw SensorValues Red: 1000 Green: 560 Blue: 400 Mapped SensorValues Red: 250 Green:140 Blue: 100
  3. Continue to the next step.

Step 9: Set the LED Light Levels

Finally, use the converted sensor data to set the brightness of the LED.

You will put the analogWrite() function into practice! Remember, analogWrite() needs two arguments: the pin to write to, and a value between 0-255 (here given by the variable redValue, etc).

  1. Copy the code into the Code Editor: analogWrite(redLEDPin, redValue); //change color of LED analogWrite(greenLEDPin, greenValue); analogWrite(blueLEDPin, blueValue); } //end of loop
  2. Using our example values (1000, 140, 100) the red LED would be almost at full brightness, and the green and blue LEDs would be very dim. The LED would have a pinkish color!
  3. This is the end of the program! Continue to the next step.
  4. Stuck? HINT: Don't forget to include the {curly bracket} to end the loop() function.

Step 10: Use It! (simulator)

When your code is finished, press "Upload & Run." The simulator will start running.

You can simulate the amount of relative red, green, and blue light hitting the sensors by highlighting each sensor and moving the slider from left to right.

  1. Upload the Arduino code to the board! It will automatically start running.
  2. Once you have your Arduino programmed and wired up, open the serial monitor. The three photoresistors are not receiving any light yet so the LED should be turned off or very dim.
  3. Try moving all of the sliders up to the maximum value. The LED will turn white! Look at the values from the serial monitor - they should all be identical.
  4. Try moving one or two sliders at a time to simulate different colors of light! Observe the change in LED color.
  5. Next, move the slider on the first sensor (red) all the way off. What color is the LED now? (see hint)
  6. Continue to the next step for instructions using the Arduino kit.
  7. Stuck? HINT: The color of the LED should match the colors hitting the sensors: when red is turned off, the remaining green and blue light mix to create a turquoise color.

Step 11: Use It! (Arduino Kit)

Once you have your Arduino programmed and wired up the LED will probably be an off-white color, depending on the predominant color of the light in your room. When you look at the sensor values in the serial monitor, the number should probably be fairly consistent if you’re in an environment with stable lighting.

An example of the serial data is shown below (expand image).

  1. Upload the program to the Arduino Uno and open the serial monitor.
  2. Turn off the light in the room you\u2019re in and see what happens to the values of the sensors.
  3. Instruction image With a flashlight, illuminate each of the sensors individually and notice how the values change in the serial monitor, and how the RGB LED color changes. When the photoresistors are covered with a gel, they only react to light of a certain wavelength. This gives you the opportunity to change each of the colors independently!
  4. Continue to the next step.
  5. Stuck? HINT: You may notice that the photoresistor's output doens't range all the way from 0 to 1023. That's ok for this project, but for a more detailed explanation of how to calibrate a sensor, try the project called Light Theremin.

Step 12: Interpreting the Results

You’ll probably notice that the LED’s fading is not linear. When the duty cycle is 50%, we expect the LED to have half-brightness, but it appears to be fully bright.

This is because our eyes don’t perceive brightness in a linear way. The brightness of the light depends not only on the level that you analogWrite() but also on the distance of your eye from the light, and the brightness of the light relative to other light in the room.

  1. Continue to the next step.

Step 13: Think About It...

How could you use this project to let you know if it's a nice day outside while you're working inside? What other sorts of sensors would you use to control the LED's color?

  1. Continue to the next step.

Step 14: Review

Congratulations on finishing the color mixing lamp!

You are no longer limited to just turning lights on and off with a button. You now have control over how bright or dim something will be. analogWrite() is the function that allows you to control the magnitude of an output using pulse width modulation (PWM) to vary the duty cycle. Components attached to pins 3, 5, 6, 9, 10, or 11, can be controlled by PWM!

  1. Continue to the next lesson for some advice on making the project look a little cooler!

Next Lesson:Adding a Light Diffuser

About This Instructable




More by circuits:Introduction Arduino Project 15: Hacking Buttons Arduino Project 14: Tweak the Arduino Logo 
Add instructable to: