Lego NXT-RobotC ultrasonic sensor

Tag: robot , nxt , lego Author: CX99720361 Date: 2013-04-05

I am newbie in programming so I need help with my Ultrasonic sensor driven NXT robot. It is attached to motor(A) and I'd like it to scan the room from robot's centerline to 90° left and 90° right in 30° increments (seven measurements total), store the data to an array and based on largest distance point my robot in the direction that measurement was taken to avoid obsticles. Is this possible at all? Or is there some better solution? Any advice or suggestion is more than welcome.

Other Answer1

This would work somewhat for avoiding obstacles, as for implementing it, it depends what you are programming the robot in. I only know lejos(java), in which a function for getting the angle to go would be something like:

public static int scanArea(RegulatedMotor motorTop, UltrasonicSensor sonar) {
    int theAngle = 0;
    int largestDist = 0;
    int currentDist;
    for (int rotateAngle = -90; rotateAngle <= 90; rotateAngle += 30) {
        motorTop.rotateTo(rotateAngle);
        currentDist = sonar.getDistance();
        if (currentDist > largestDist) {
            largestDist = currentDist;
            theAngle = rotateAngle;
        }
        Delay.msDelay(25);
    }
    motorTop.rotateTo(0);
    return theAngle;
}

If you're coding the robot in any code based language that should be fairly easy to convert (assuming you have functions such as rotateTo, otherwise you would have to use relative movements). Otherwise I don't know how easy this would be to do in the graphical programming language that you use originally.

comments:

Thank you Andreas for answering with a speed of light :)
I'm programming using RobotC and there's no "rotateTo" function but MotorEncoderTarget looks close..."motorTop" in youe example is the "name" of motor involved?
motorTop is just the name of an object that is an instance of the RegulatedMotor class which contains methods for controlling a motor.

Other Answer2

I would suggest attaching the ultrasonic sensor to a 180° servo that is vertical. You can take a measurement at a specific degree by assigning that degree to the servo. Using this:

int largestDistance = 0;
int Angle =0;    

for (int servovalue = 0; servovalue <= 255; rotateAngle += 30){
        Servo[servo1] = servovalue;
        if (SensorValue[Sonar] > largestDist) {
            largestDist = SensorValue[Sonar];
            Angle = servovalue;
        }
    }
    return Angle;
}

It assumes that servo1 is your vertical servo, but this should work if your programming in RobotC.