LEGO Mindstorms

Ultrasonic Sensor

Understanding sensor input and the ultrasonic sensor

What are sensors?

Sensors are devices that detect or measure physical properties. Essentially, they tell the robot about important information like the robot’s position, distance to an object, temperature, color, light, motor rotation, and whether or not the robot has touched something. All of this information can be used to decide how the robot should move.

For instance, we can tell a robot to stop moving once it hits a wall by using the touch sensor to detect contact. If the touch sensor is pressed, then the robot should stop. Similarly, we can use a light sensor to decide whether or not to turn on a light on the robot. If its very dark, then we can get the robot to turn on the light, whereas, if its too bright, then we can get the robot to turn off the light. 

Aside from if/then or /“switch/” statements, we can also use sensors to decide whether to continue running a loop or not. For instance, we could use the ultrasonic sensor to check if we are close to a wall or not, and drive towards it until the robot is very close. That is, While the distance to the wall is more than 20 centimeters, keep driving. Clearly, sensors are very valuable to robots. They are what make robots capable of doing things on their own and responding to changing conditions!

What does the Ultrasonic Sensor do?

The Ultrasonic Sensor generates sound waves and reads their echoes to detect and measure distance from objects. It can also be used to detect sounds, but it is most useful as a distance sensor, so to speak. We use this sensor to measure the robot’s distance from objects. We can use this sensor to see if any objects are in the robot’s path, and if so, perform a different plan of action. To select the ultrasonic sensor, open a loop or switch, and then choose the device for the condition as the ultrasonic sensor.

Ultrasonic Switch

For example, if the robot is less than 10 cm from a wall, then play a sound! The switch statement would look something like this:

In this if statement, if the ultrasonic sensor sees less than (green) 50cm away (blue), then the robot will make a sound and then drive forward. 

Ultrasonic Loop

Also, we can use this sensor, as stated above, as a condition for a loop. For example, we can create a program where our robot drives until it reaches a certain distance from a wall or object on the game field. We can do this using the following code:

In the code above, we set the loop such that it continues to run as long as the distance measured by the ultrasonic sensor is greater than (green) 50cm (blue). If the distance measured is more than 50cm, then the loop will stop and the commands inside it will no longer be run. The code will proceed to the next block of code outside the loop.

chevron_up