Ultrasonic Sensor

Measure distance from object in centimeters


Simulink Support Package for LEGO MINDSTORMS NXT Hardware


Measure the distance between the LEGO MINDSTORMS 9846 Ultrasonic Sensor and the nearest object in front of the sensor.

The sensor can detect objects from approximately 5 to 255 centimeters away. When the nearest object is beyond the maximum range of the Ultrasonic Sensor, the sensor outputs the maximum value, 255.

The measured distances are approximate. For greater precision, calibrate the sensor output values against physical measurements.

The distance from which the sensor first detects an approaching object depends on:

  • The ultrasonic reflectance of the object, which is a function of the object's size and composition. The sensor detects large hard objects from a greater distance than small soft ones. For example, the sensor might detect a pane of glass at 255 cm and a hand puppet at 150 cm.

  • The angle of incidence of the object relative to the sensor. The sensor detects objects directly in front of it at greater distances than objects off to the sides.

If you run a simulation of a model that contains this block without the target hardware, this block outputs zeros. See Block Produces Zeros or Does Nothing in Simulation.

Use the Ultrasonic Sensor

With the following blocks, the output from ultrasonic sensor drives the motor forward. As the ultrasonic sensor approaches an obstacle, the output values decrease, slowing the motor.

  1. Open the legonxtlib block library and copy the blocks shown to a new model.

  2. Connect the Ultrasonic Sensor block to the Motor block, as shown.

  3. Connect the ultrasonic sensor to Port 1 on the NXT brick, and connect the servo motor to Port A on the NXT brick.

  4. Prepare and run the model on the NXT brick.

  5. Observe the speed of the motor decrease as you hold the ultrasonic sensor closer to an object.


NXT brick input port

Select the NXT sensor port to which the sensor is connected. Avoid assigning multiple devices to the same port. The options are 1, 2, 3, or 4.

Sample time

Specify how often the block reads sensor values. This value defaults to 0.1. Shorter sample times, such as 0.01, may produce unreliable measurements.

Smaller values require the processor to complete the same number of instructions in less time, which can cause task overruns.

Was this topic helpful?