A Simple Color Sensor

paige

A Simple Color Sensor

What's Happening:

Here's a relatively simple color sensor using a photo resistor and a RGB LED. This LED cycles through each color with the magic of PWM. When an object is held up to the LED, the light bounces off the object and is picked up by the photo resistor. Then the value is then converted into a Hex color code and viola! We have a color sensor that is fairly accurate...

How It's Made:

Not a lot of hardware went in to the making of this project. To build this, you'll need:

  • Fancy-pants computer with USB ports and everything

  • Arduino UNO (with installed Arduino IDE on your computer)

  • Three 220 Ohm resistors

  • RGB LED

  • One 1k Ohm resistor

  • Photo resistor

  • USB Cable

  • Breadboard

  • Assorted jumper wires in all your favorite colors

Setup:

The wiring is pretty simple and you can take a look at it here When wiring this project, I would highly suggest putting the LED and the photo resistor as close together on your breadboard as possible. I noticed that I tend to get a more accurate reading when I have them close together.

So, after you've set up your Arduino, you need to flash it with a software called Firmata (Take a look at the explanation below to find out what Firmata is). To do this, go to the Arduino IDE that you previously installed and select: File > Examples > Firmata > Standard Firmata

Click the "Upload" button and there you have it, your Arduino is ready to go. Once you've done that, go ahead and close Arduino IDE, since you won't be using it anymore for these node.js projects.

But wait, there's more, you'll need to download Node.js and you will also need Python 2.6. Oh, and don't forget Visual Studio Express 2012. We won't really be talking about these but if you're interested in them, start with a good old fashioned google search.

Now you need to go to your command prompt terminal. In this you need to do a few things. First, create a new directory to keep all your lovely codes. To do this, type mkdir nodebot and press enter. The "mkdir" stands for "make directory" and "nodebot" is the name of the directory I chose, you can name yours whatever you want. Now you should type cd nodebot and press enter to change directories. You need to be in the directory you created to house your files. When you're done with that, install Johnny-Five. Johnny-Five is this nifty API (application programming interface) that can do lots of cool things and stuff. To install it, jump into your terminal and type npm install johnny-five then press enter. Be patient and read over the documentation for Johnny-Five or something while you wait for it to install. You know you're doing it right if you get a bunch of lines with values similar to this: npm http GET https://registry.npmjs.org/johnny-five

Okay, we're mostly set up now. The next step is to copy paste the code below into a text file. I like Notepad++, which you can download via the link. Once you've copied it, save it as a .js file in the directory you made. You'll find this directory in your C drive, under "Users", then by its name.

Let's Get To Work:


var
    five = require('johnny-five')
    , LEDs
    , board
    , photo         // photo resistor
    , state = 0     // current color (0 = r, 1 = g, 2 = b)
    , duty = 255    // current duty cycle
    , maxPhotoValue = 0 // highest photo resistor value
    , maxHue = [ ]    // color values at time of highest photo resistor value
    , timer            // loop
    , red
    , green
    , blue
    , idle    // boolean: is the sensor taking a reading?
    ;

    board = new five.Board();

    board.on('ready', function() {
    red = new five.LED(9);
    blue = new five.LED(10);
    green = new five.LED(11);
    LEDs = [ red, green, blue ];

    photo = new five.Sensor({
        pin : "A0"
        , freq : 200
    });

    photo.on('read', function(err, dat) {
        if(err) { return console.log(">>> Read error: %s", err); }
        //console.log("Raw value: %s, normalized: %s", dat, this.normalized); //this prints the photo resistor values, and if you'd like to see them, remove the slash marks from the front of the command

    });

    function stepColor() { //start cycling through the colors
        stateCheck();
        colorCheck(); //and while you're at it, check what color the object is
        LEDs[state].brightness(duty);
        LEDs[(state + 1) % 3].brightness(255 - duty);
    };

    function stateCheck() {
        if(--duty > 0) {
            return false;
        }
        duty = 255;
        if(++state == 3) {
            // done with scan
            state = 0;
            console.log(">>> %s", rgbToHex(maxHue));
        }
        return true;
    };
    setInterval (stepColor, 10)

    function colorCheck() {
        if(photo.value > maxPhotoValue) {
            maxPhotoValue = photo.value;
            maxHue = [
                red.value
                , green.value
                , blue.value
            ];
        }
    };

    function componentToHex(c) {
        if(c == null){
            return;
        }
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    };

    function rgbToHex(vals) {

        return [
            "#"
            , componentToHex(vals[0])
            , componentToHex(vals[1])
            , componentToHex(vals[2])
        ].join('');
    };
});

It's important to understand what this code does and a good way to become proficient with coding is to read over the code and figure out what each of the commands means.

So, now that you've saved it, you can go back to your terminal window. Make sure you are in the correct directory, via the cd nodebot command you used previously, and type node filename.js and press enter. The "filename" corresponds to the name you saved the text file as in your directory.

Hopefully, you should have some fancy stuff pop up in your terminal window, telling you what COM port your Arduino is on and various other things that are being initialized. If you don't, take a look at the common errors below. Your Arduino should also begin cycling through the LED colors. This would be the time to start putting objects in front of the sensor. Pretty soon, the cycle will restart and the terminal window will spit out some weird six digit numbers and letters known as Hex codes. See below if you'd like to understand the data you're getting and what it means.

This code will continue to cycle through the colors and spit out values, so you can keep switching objects and testing the code. I used color construction paper which seemed to work quite well, since it's a uniform color.

What Does It Mean?

So, the terminal spits out Hex values that look something like this:

>>> #01d926

>>> #ad5201

>>> #016b94

etc...

And these values don't really mean anything until you understand what Hex Code is and why it's cool. If you're new to it like I was, here's a basic overview of how it works. The six digit code is broken up into three pairs (#RRGGBB) and these pairs determine the amount of each color that is present. But why are there letters in there if it's supposed to be numeric? Well, the numbers go from 0 to 9, and the letters are associated with the numbers 10 through 15. So before you go and punch these seemingly meaningless numbers into a search bar, try to dissect them. The pair with the biggest value is going to tell you the overriding color. so >>> #ad5201 would mean that the first pair is the most prominent, therefore it has a lot of red in it. The actual color is more brownish, but it is more than 67% red, so we're going to categorize it as red.

Common Errors:

  • I keep getting errors when I try to install Johnny-Five!

Make sure you have the proper version of Python installed. (2.6 and 2.7 are both acceptable).

You could also try specifying the Visual Studio version in your terminal window by typing npm install johnny-five --msvs_version=2012 when you install Johnny-Five.

Also, it's important you have Visual Studio Express 2012, you may have luck with 2010, but I have never tried it.

  • I am getting a device or firmware error!

Have you flashed your Arduino with Standard Firmata? If you have compiled Arduino codes to your Arduino using the IDE recently instead of node.js codes, you will have to re-flash it.

Why Does It Work?

Nifty physics of light and such. As the RGB LED cycles through its colors, it reflected light off the object in question. Let's say we had a red object that was being sensed, the object would reflect the red light and absorb the green and blue light, which would give the photo resistor a very high value when the LED cycled through red. This tells the arduino that it has a red object in front of it.

What's Firmata?

Firmata is a generic protocol that is used for communicating with microcontrollers from software on a host computer. In this project, we run our node.js code and Firmata talks to the Arduino. Isn't that neat?

What About Johnny-Five?

Johnny-Five is an open source JavaScript Arduino programming framework. You can read more about it here.

comments powered byDisqus