Package com.cos399.goalfind.sensors

Source Code of com.cos399.goalfind.sensors.GoalFindUltrasonicSensor

/*  Class controls the ultrasonic sensor and sweep motor.  All data gathered
*   is reported to the DataExchange object. */

package com.cos399.goalfind.sensors;

import com.cos399.goalfind.dataexchange.DataExchange;

import lejos.nxt.MotorPort;
import lejos.nxt.NXTRegulatedMotor;
import lejos.nxt.SensorPort;
import lejos.nxt.UltrasonicSensor;

public class GoalFindUltrasonicSensor extends Thread {
 
  private static GoalFindUltrasonicSensor goalFindUltrasonic = null;
  private static UltrasonicSensor ultrasonicSensor = null;
  private static NXTRegulatedMotor sweepMotor = null;
  private static DataExchange de = null;
 
  private final static int securityDistance = 25, sweepAngle = 90, sweepSpeed = 50;
  private boolean leftSweep = false;
 
  private GoalFindUltrasonicSensor() {}
 
  public static GoalFindUltrasonicSensor getInstance() {
    if (goalFindUltrasonic == null) {
      goalFindUltrasonic = new GoalFindUltrasonicSensor();
      ultrasonicSensor = new UltrasonicSensor(SensorPort.S4);
      sweepMotor = new NXTRegulatedMotor(MotorPort.B);
      de = DataExchange.getInstance();
      sweepMotor.setSpeed(sweepSpeed);
    }
   
    return goalFindUltrasonic;
  }
 
  /*  Handles the execution of this class via a while loop to constantly check
   *   for the distance.  If the distance is less than the boundary, the sweep
   *   motor stops and data values are updated.  Once these operations are complete,
   *   the sweep action continues
  */
 
  @Override
  public void run(){
   
    while(ultrasonicSensor.getDistance() > securityDistance){
      executeContinuousSweep();
    }
   
    sweepMotor.stop();
    updateDataValues();
   
    run();
   
  }
 
  //handles the sweep of the motor in 180 degree rotations
  private void executeContinuousSweep(){
    if (leftSweep){
      sweepMotor.rotate(-sweepAngle * 2, true);
      leftSweep = false;
    } else {
      sweepMotor.rotate(sweepAngle * 2, true);
      leftSweep = true;
    }
  }
 
  /*  Calculates the angle of incidence to the obstacle and records it to
   *   the data exchange object
   */
  private void updateDataValues(){
    int angle = 0;
   
    if (leftSweep){
      angle = Math.abs(sweepAngle - sweepMotor.getPosition());
    } else {
      angle = Math.abs(sweepAngle + sweepMotor.getPosition());
    }
   
    de.setCmd(0);
    de.setUltrasonicDetected(true);
    de.setAngleDetected(angle);
  }
 
 
}
TOP

Related Classes of com.cos399.goalfind.sensors.GoalFindUltrasonicSensor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.