Main Content

readDistance

Distance to object in front of ultrasonic sensor

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 anarduinoobject withUltrasoniclibrary.

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 anultrasonicobject.

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 returnsInf.

Data Types:double

Introduced in R2019a