Lesson: Exercise: Using a Color Sensor
Learn how to use the Color sensor.
The Color Sensor is used to determine the amount of light reflected from a surface and also the color of the reflected light. The Color Sensor is typically used in line following applications where the surface is the table the robot is operating on. The Color Sensor must be close to the surface, usually about 1 cm to work well. The sensor has a multi-color LED (called the floodlight) that can be used to illuminate the surface. The Color sensor is more complicated than the other sensors. It has several modes of operation:
Mode | Description |
---|---|
ColorID | Returns a numeric value that maps to a single color. Values can be found in the lejos.robotics.Color class. Only recognizes basic colors. |
Red | Returns light level (brightness) of Red light. Red floodlight LED should be turned on. Red light offers better detection of light levels. |
RGB | Returns a lejos.robotics.Color object with the Red, Green and Blue values set according to the brightness (intensity) of those colors detected. |
Ambient | Returns the ambient light level detected. |
You must select the appropriate mode for your application and you will probably need to experiment to determine which mode works best.
As we have done with the other sensors, we have a library class called ColorSensor that simplifies using the EV3ColorSensor. Create a new class called ColorSensor in the library package and copy this code into that class.
Next, in ev3.exercises create a new class called ColorDemo. Copy the following code into that class:
This program demonstrates each mode of the Color sensor. After the wait for start, the ambient light intensity is displayed. You can hold the EV3 in your hand or better yet put on various surfaces to see the values returned by the sensor. When done with ambient, press the escape button to move to the next mode. That mode measures the red light intensity with the red LED turned on. Press the escape button again to move to displaying the RGB color detected. Note we turn on the white light on the LED to better detect actual surface color. Press the escape button again to move to detection of a single color value. This color value is a numeric value, so to make our lives easier, the ColorSensor class has a method to convert the numeric color value to a color name.