Basic Distance Sensor Programming


The distance sensor uses ultrasonic sound waves to measure distance. With the distance sensor, your robotic inventions can detect and navigate around obstacles. The distance sensor measures distances from 1 inch to 10 feet, and because it uses sound waves, the sensor is more accurate in detecting flat surfaces than curved ones.

In this tutorial, you will learn about the distance sensor and measure the distance to the closest detected object. You will also program the VEX IQ brain to print a message when it has detected an object within a set range.

Hardware Requirements

  • VEX IQ Brain
  • Distance Sensor

Program

Let's create a program that measures the distance to the closest detected object.

Open the Modkit for VEX editor. Drag and drop a distance sensor and assign its port number. Make sure it matches that of the physical distance sensor.

Next, click on the 'Blocks' tab and make sure that you are editing the 'Brain'. Drag code blocks to match the image below. The 'when START' block runs once each time your program runs. The 'forever' block repeatedly runs the code inside, allowing your program to change and respond as it runs.

Download your program and run it on the physical VEX IQ brain. We've provided a graphic that you can use to test your program (see attachments below); simply print out the graphic, and assemble the barrier as instructed on the print out. You can make as many barriers as you'd like. Point the distance sensor at a barrier, and observe the distance value printed on the brain.

Next, let's modify the program to detect objects within a set distance. Drag and drop code blocks to match the image below. Set the distance range to 100mm. If an object is detected in the range, the message, "STOP! Object detected" will appear on the VEX IQ brain. Otherwise, the message "All clear!" will be printed.

Download your program and run it on the physical VEX IQ brain.

In this tutorial, you learned about the distance sensor, read the distance to the closest detected object, and printed messages based on the distance measured. There is so much more that you can do! Check out our other Getting Started guides!

Updated 47 months ago

What You'll Need