The EV3 Ultrasonic Sensor measure distances within a range of 1 and 250 cm with an accuracy of +/- 1 cm. The sensor is useful for detecting and avoiding obstacles.
The getDistanceMode method returns the current distance from an obstacle, in centimeters.
It's important to note that the Ultrasonic sensor is located at the front of the robot, but it does not stick out as much as the other sensors. This means that when the robot hits a wall, the ultrasonic sensor is still a few centimeters away from the wall and its reading will show a value of a few centimeters.
Here is an example code showing how to stop the robot when it is less then 20 cm away from the wall:
As a bonus, we also added a Print block within the loop to print the current distance to the console.