/***********
 *
 * A Bumper object for the lego robots.
 * 
 *   Usage: 
 *     Bumper leftBumper = new Bumper( Sensor.S1, "in by default" );
 *     if (leftBumper.wasHit()){ ... }
 *
 * @author Jim Mahoney
 * @version 1.0, Oct 14 2002
 * 
 ******/

import josx.platform.rcx.*;

public class Bumper { 
    
    private Sensor  itsSensor;
    private boolean inWhenNotPushed;

    /**
     * Create a new Bumper object.
     * @param s One of the three sensors, i.e. Sensor.S1, S2, or S3.
     * @defaultPosition of the bumper,  "in" or "out". 
     **/
    Bumper( Sensor s, String defaultPosition ){
	itsSensor = s;
	char firstChar = defaultPosition.charAt(0);
	inWhenNotPushed = ( (firstChar=='I') ||  (firstChar=='i') );
	itsSensor.setTypeAndMode(SensorConstants.SENSOR_TYPE_TOUCH,
				 SensorConstants.SENSOR_MODE_EDGE);
	itsSensor.activate();
	itsSensor.setPreviousValue(1);
    }

    /**
     * @return true if the bumper is currently being pushed in.
     **/
    public boolean isIn(){
	if ( inWhenNotPushed ){
	    return (! itsSensor.readBooleanValue() );
	}
	else {
	    return itsSensor.readBooleanValue();
	}
    }

    /**
     * @return true if the bumper is currently in its normal extended position.
     **/
    public boolean isOut(){
	return ( ! isIn() );
    }

    /**
     * Returns true once when the bumper is pushed in.
     * Successive calls return false, even if the bumper stays pushed in,
     * until after the bumper returns to its default position.
     **/
    public boolean wasHit(){
	boolean returnValue = (itsSensor.readValue() > 1) ;
	if (itsSensor.readValue()>1) {
	    itsSensor.setPreviousValue(0);
	}
	return returnValue;
    }
}


syntax highlighted by Code2HTML, v. 0.9.1