How to use the Ultrasonic Sensor with Arduino

How to use the Ultrasonic Sensor with Arduino

Ultrasonic Sensor for Arduino


Ultrasonic sensors are transceivers that send and receive signals and work on a principle similar to sonar or radar. Ultrasonic sensors generate high frequency sounds waves and determine the position of an object by the echo that is received back. The time interval between sending and receiving the signal will determine the distance of the object.


Any form of movement or distance detection such as anti-collision detection, human, animal or object detection/distance measurement. Many production lines in factory automation use some form of the Ultrasonic Sensor to optimize and operate. Their small sizes make it easy to integrate with machines and robots in many configurations. In robotics and automation, the ultrasonic sensors are used in applications such as:

  • object detection
  • detect the position of an object
  • measure the distance between the sensor and an object
  • counting the objects which pass through the front of the sensor
  • tracking the movement and distance of an object


VCC – 5V

TRIG – Digital Pin 2

ECHO – Digital Pin 3


Ultrasonic Sensor Arduino


// Standard declaration of pins
int trigPin = 2;    // Trigger
int echoPin = 3;    // Echo
float duration, distancecm, distanceinches;
void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT); //triggering a sound to bound off an object
  pinMode(echoPin, INPUT); //receiving the sound bounce (echo) from trigger
void loop() {
  // Standard good measure to include this code ensure a clean pulse signal from the sensor
  digitalWrite(trigPin, LOW);
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);

  //setting receiving pin to INPUT again
  pinMode(echoPin, INPUT);
  //duration (in microseconds) it takes for the sound wave to be sent from sensor to object and return
  duration = pulseIn(echoPin, HIGH);
  // Convert the travel time of sound into distance, distance = time x speed of sound
  distancecm = (duration/2) / 29.1;     //  or multiply (duration/2) by 0.0343 cm/microseconds
  distanceinches = (duration/2) / 74;   //  or multiply (duration/2) by 0.0135 inch/microseconds
  //printing the output in readable form
  Serial.print("Distance: ");


Open the serial monitor and see distance measurement output.

Note that you can Google speed of sound in inches per microseconds.

Note you can Google speed of sound in cm per microseconds.

Everything in Arduino is measured in Microseconds.