The Ultrasonic Sensor

The ultrasonic sensor measures distance. One of the “eyes” transmits a sound, and the other waits for the echo of the sound to return. From the time this process takes, the distance of the object from the sensor can be calculated. The ultrasonic sensor has a range of 3-400cm. If an object is outside this range, the sensor will return a value of 400.


In this lesson, I want to get the robot to go forward until it is close to an object, then turn away from the object and go off in a new direction:

---- If an object is detected
---- ---- Turn to a new direction
---- Else
---- ---- Go forward

And in code, that looks like this:


On testing this, I found that the robot wasn’t turning enough when it encountered an object, so I added a wait command after the turn. Now I would like to get it to turn in a random direction – sometimes left and sometimes right. Fortunately, there is an Operator block that I can use to do just that:


The robot can only turn left or right, so I am going to choose a random number between 0 and 1. If the random number is 0, then the robot will turn left. If the random number is 1, then the robot will turn right. So then the turning behavior will look like this:



  1. Can you put the code above together to make the completed program?
  2. Can you write a program that follows an object? So if the object is too close, the robot goes backwards, if the object is far away, it goes forward, and if the object is not near or far, the robot stops.
  3. Can you change your program from question 2, to make the robot move at different speeds?

Construct Your Dreams!