I have an ultrasonic sensor attached to a motor so that the sensor can rotate. Right now it stops once it scans a value less than 65 cm. What I want it to do is to scan its surroundings and then face the ultrasonic sensor perpendicular to a the closest object.

task findWall() { OnFwd(OUT_C, 30); until(SensorUS(IN_4)<65); Off(OUT_BC); }

I like your username. I'm not exactly good at NXC either, but I'm experienced in C and Java. So here's some pseudocode that should get the job done. This will rotate the scanning motor 180 degrees, while remembering the closest object it's seen, and then rotating that motor back to point towards the closest object. You will need to change the functions to correspond to the actual NXC functions.

int closestObjectDist = 100; //variable records the closest object's distance
int closestObjectAngle = 0;  //variable records the angle pointing to the closest object
int currentAngle = 0;        //variable to hold the scanning motor's current angle.
int currentDistance = 0;     //variable to hold the sensor's current distance reading

resetScanningMotorAngle();   //reset the scanning motor's angle to 0.
turnScanningMotorOn(10);     //start rotating the scanning motor, slowly.

while(currentAngle < 180)    //repeat until the scanning motor has rotated 180 degrees
{
    currentAngle = getScanningMotorDegrees();  //get the motor's current angle
    currentDistance = readUltrasonicSensor();  //get the sensor's current distance

    if( currentDistance < closestObjectDistance )  // Here's the important part:
    {                                              // When the sensor reads a distance that
        closestObjectDistance = currentDistance;   // is the smallest distance yet,
        closestObjectAngle = currentAngle;         // record the angle and distance.
    }
}
                                            //now we have the closest object's angle stored!
rotateScanningMotorTo(closestObjectAngle);  //rotate the motor back to the recorded angle.  

This code assumes that the robot scans in a 180-degree arc, but you could easily just change the 180 to 360 to scan in a full circle.

After the loop, you can add or subtract 90 degrees to closestObjectAngle to make the motor point perpendicular to the closest object instead of pointing AT the closest object.

Ask if you have any questions!

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.