javanxt

ColorSensor LeJos NXT


So, basically what i'm trying to do is:

i let my NXT drive a parkour, and while he's doing that, he has to display the colors of a piece of paper (he drives over the paper) on the LCD.

The colors are red, green and blue.

The one thing that's not working is: reading or "seeing" the color and displaying them on screen.

the code i got now is :

    ColorSensor cs = new ColorSensor(SensorPort.S1);
    Color color = cs.getColor();

    int groen = color.getGreen();
    int rood = color.getRed();
    int blauw = color.getBlue();

    String text = "";

    if (color.getColor() == groen){
        text = "groen";
    }
    else if (color.getColor() == rood ){
        text = "rood";
    }
    else if (color.getColor() == blauw ){
        text = "blauw";
    }


    LCD.drawString("kleur is: " + text, 0, 0);
    Thread.sleep(6000);

Solution

  • The getters of the Color object don't return any green, blue or red constant values, they tell you how green, red or blue is the detected color, from 0 to 256.

    For example, a yellow-ish color should return a low red component, and higher blue and green values, very similar between them.

    You could try something like:

    ColorSensor cs = new ColorSensor(SensorPort.S1);
    Color color = cs.getColor();
    String text;
    
    if (color.getGreen()>color.getRed() && color.getGreen()>color.getBlue()) {
        text="green";
    } else if (color.getBlue()>color.getRed() && color.getBlue()>color.getGreen()) {
        text="blue";
    } else {
        text="red";
    }