ColorSensor.java
import lejos.nxt.*;
/**
 * A sensor that is able to distinguish a black/dark surface
 * from a white/bright surface.
 * 
 * Light percent values from an active light sensor and a
 * threshold value calculated based on a reading over a 
 * black/dark surface and a reading over a light/bright 
 * surface is used to make the distinction between the two 
 * types of surfaces.
 *  
 * @author  Ole Caprani
 * @version 23.08.07
 */
public class ColorSensor {
 
   private LightSensor ls; 
   private int blackLightValue;
   private int whiteLightValue;
   private int blueLightValue;
   private int blackBlueThreshold;
   private int blueWhiteThreshold;
 
   public ColorSensor(SensorPort p)
   {
       ls = new LightSensor(p); 
       // Use the light sensor as a reflection sensor
       ls.setFloodlight(true);
   }
 
   private int read(String color){
 
       int lightValue=0;
 
       while (Button.ENTER.isPressed());
 
       LCD.clear();
       LCD.drawString("Press ENTER", 0, 0);
       LCD.drawString("to callibrate", 0, 1);
       LCD.drawString(color, 0, 2);
       while( !Button.ENTER.isPressed() ){
          lightValue = readValue();
          LCD.drawInt(lightValue, 4, 10, 2);
          LCD.refresh();
       }
       return lightValue;
   }
 
   public void calibrate()
   {
       blackLightValue = read("black");
       whiteLightValue = read("white");
       blueLightValue = read("blue");
       // The threshold is calculated as the median between 
       // the two readings over the two types of surfaces
       blackBlueThreshold = (blackLightValue + blueLightValue)/2;
       blueWhiteThreshold = (blueLightValue + whiteLightValue)/2;
   }
 
   public boolean black() {
           return (readValue() > blackBlueThreshold);
   }
 
   public boolean blue() {
       return (readValue() < blackBlueThreshold && readValue() > blueWhiteThreshold);
   }
 
   public boolean white() {
       return (readValue() < blueWhiteThreshold);
   }
 
   public int light() {
        return readValue();
   }
 
   public int readValue() {
       return SensorPort.S1.readRawValue();
   }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License