Introduction: Distance Measuring Using UltraSonic Sensor and Arduino

About: Page owner Sameen Solkar Email :

In this project we are going to measure distance using ultrasonic sensor and the measured distance value will be displayed on computer screen.

We will be using Processing 3 software to display the distance on the compter screen.


For this project we need:

  • Arduino uno
  • Ultrasonic sensor HC-SR04
  • BreadBoard jumper wires

Step 1: Theory Behind Measuring Distance

The Sensor works on the phenomenon of Echo of sound.

In order to generate the ultrasound you need to set the Trig on a High State for 10 µs. That will send out an 8 cycle sonic burst which will travel at the speed sound and it will be received in the Echo pin. The Echo pin will output the time in microseconds the sound wave traveled.

As speed of sound is 340 m/s (0.034 cm/us) we can calcute the received echo signal pulse duration and hence the formula for calculating distance is

Distance = (Echo pulse Duration) * 0.034 / 2

Dividing by two is done because the same wave is transmitted and received back

Step 2: Arduino Code and Connection

// connection of Sensor to arduino pin

const int trigPin = 9; //Trigger pin to pin 9

const int echoPin = 10; // Echo pin to pin 10

long duration;

int distance;

void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); } void loop() { digitalWrite(trigPin, LOW); // Clears the trigPin

delayMicroseconds(2); digitalWrite(trigPin, HIGH); // Sets the trigPin on HIGH state for 10 micro seconds

delayMicroseconds(10); digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds

// Calculating the distance distance= duration*0.034/2;

duration = pulseIn(echoPin, HIGH);

//Sending distance value to serial port Serial.println(distance); delay(500); }

Step 3: Processing 3 Code

import processing.serial.*;

String distance = "00";

void setup() {


//Enter COM port to which your arduino is connected (mine was COM5)

Serial port = new Serial(this, "COM5", 9600);



void draw() {


textSize(72); fill(37,236,0);

text("Distance",50, 100);


text(distance,70, 200);


text(" cm", 200, 200);


void serialEvent (Serial port) {

distance = port.readStringUntil('\n');