/********************************************
* LightSensor is a class to intialize
* and manage one of the Lego Brick RCX optical sensors.
*
* Typical use is to put the LegoBrick over "white" space and
* then call the defineWhite() routine.
* After that, calls to seesWhite() will return true
* if getValue() sees a shade within "tolerance" of
* that value, so that the lego robot can tell whether its
* over a shiny or dark patch of floor.
*
* The "black" colors works the same way. These names are
* arbitrary; the reflectivity to match is set by what
* the sensor is looking at.
*
* The code from the caller might look something like this.
*
* // Put the robot on a white patch. Push the PRGM button.
* // Put it somewhere else. Push the RUN button.
* LightSensor ls = new LightSensor(Sensor.S3);
* while (true) {
* if (Button.PRGM.isPressed()){ ls.defineWhite(); }
* if (Button.RUN.isPressed()) {
* // run around the floor ...
* if ( ls.seesWhite() ) { // we're over a white patch }
* }
* }
*
* @author Jim Mahoney
* @version 1.0, Oct 11 2002
********************************************/
import josx.platform.rcx.*;
public class LightSensor {
private int whiteValue; // 0 - 100 percent, high values are whiter.
private int blackValue; // ditto
private int tolerance; // how close for a color match
private Sensor mySensor;
LightSensor(Sensor theSensor){
mySensor = theSensor;
mySensor.setTypeAndMode(SensorConstants.SENSOR_TYPE_LIGHT,
SensorConstants.SENSOR_MODE_PCT); //PCT=percent
mySensor.activate();
whiteValue = 80; // very reflective
blackValue = 20; // very absorbing
tolerance = 3;
}
public void setTolerance(int theTolerance){
tolerance = theTolerance;
}
public void defineWhite(){
whiteValue = mySensor.readValue();
}
public void defineWhite(int white){
whiteValue = white;
}
public void defineBlack(){
blackValue = mySensor.readValue();
}
public void defineBlack(int black){
blackValue = black;
}
public void lowerBlack(){
blackValue -= tolerance;
}
public void raiseWhite(){
whiteValue += tolerance;
}
public boolean seesWhite(){
return Math.abs(mySensor.readValue()-whiteValue) <= tolerance;
}
public boolean seesBlack(){
return Math.abs(mySensor.readValue()-blackValue) <= tolerance;
}
public int getValue(){
return mySensor.readValue();
}
public void turnOn(){
mySensor.activate();
}
public void turnOff(){
mySensor.passivate();
}
public void displayValue(){
LCD.showNumber(mySensor.readValue());
}
}
syntax highlighted by Code2HTML, v. 0.9.1