Main Content

readDistance

Distance to object in front of ultrasonic sensor

Add-On Required: This feature requires the MATLAB Support Package for Arduino Hardware add-on.

Description

example

distance = readDistance(ultrasonicObj) measures the distance from the ultrasonic sensor to an object and returns the measured distance in meters. The function uses 344 m/s for the velocity of sound.

Examples

collapse all

Create an arduino object with Ultrasonic library.

arduinoObj = arduino('COM9','Uno','Libraries','Ultrasonic');

Create an ultrasonic sensor connection object with the trigger pin set to D2 and echo pin set to D3.

ultrasonicObj = ultrasonic(arduinoObj,'D2','D3')
ultrasonicObj = 
  Ultrasonic with properties:

    TriggerPin: 'D2'
       EchoPin: 'D3'

Measure the distance to the object.

distance = readDistance(ultrasonicObj);

Input Arguments

collapse all

Ultrasonic sensor connection object, specified as an ultrasonic object.

Output Arguments

collapse all

Distance to object, specified as a positive real scalar, in meters. If the object is not in the range of the sensor, the function returns Inf.

Data Types: double

Version History

Introduced in R2019a