Help with Vexcode Ultrasonic sensor

I don’t know where to start with programming a ultrasonic sensor. I want my robot will drive forward and then stop when it comes close (say 5 inches) to an object. Can anyone help me with the basics of this?

Because of your topic, I am assuming you are using VexCode Text. Here is a link to the sonar API: https://api.vexcode.cloud/v5/html/classvex_1_1sonar.html
Ive never used the sonar with v5, but heres an example program I would write:

leftMotor.spin(directionType::fwd, 50, velocityUnits::pct);
rightMotor.spin(directionType::fwd, 50, velocityUnits::pct); // Drive forward at half speed

while(sonar.value(distanceUnits::in) > 5.0) { // Create a while loop to run while we are farther than 5 in from an object
   task::sleep(10); // Short delay to prevent wasting resources
}

leftMotor.stop(); //stopping motors after the loop finishes
rightMotor.stop();

I havent compiled this yet, so don’t know if it will work.

4 Likes

Heres another vexforum post I found talking about the sonar sensor: Legacy Distance Sensor on V5

1 Like

There’s also a sample program using this sensor in VEXCode.

2 Likes