working of ultrasonic sensor and interfacing with Arduino

The ultrasonic sensor HC-SR 05 is one of the most accurate and commonly available sensors to measure distance. In this article, we get to know the working of ultrasonic sensor, Connection with Arduino, and serial monitor output of distance.

Ultrasonic sensor working

Ultrasonic sensor HC-SR 05 works on ultrasonic sound waves. Transmiter emit ultrasonic sound waves, That sound is reflected by an object. Reflected sound is received by reciver.

Distance can be calculated by simple formula Distance=Time x speed of sound/2.

The speed of the ultrasonic waves in the air is 340 Meters/Second, Time taken by the wave is measured by the sensor. For exact distance, the result will be divided by 2 because the original result is a total of travel forward and bounce backward.

Pin out HC-SR 05

Ultrasonic sensor hc-sr04 have 4 pinouts VCC, Trigger, Echo, GND.

Material Required

Jumper wiresas per requirement
Ultrasonic sensor1


Trig of ultrasonic sensor to arduino pin number 9. Eco to arduino pin number 10.


// Interfacing Ultrasonic sensor with Arduino uno
#define echoPin 10 //connect echo pin of ultrasonic sensor to D10 of Arduino
#define trigPin 9 //connect trigger pin of ultrasonic sensor to D9 of Arduino
long duration;  // declare variables to hold duration and distance
int distance;
void setup() //setup() is used for initialization
 Serial.begin(9600);  //set the baud rate of serial communication to 9600
 pinMode(trigPin,OUTPUT); //set trigPin as output pin of Arduino
 pinMode(echoPin,INPUT);  //set echoPin as output pin of Arduino
void loop(){
 digitalWrite(trigPin,LOW); //generate square wave at trigger pin
 duration=pulseIn(echoPin,HIGH);//calculation of distance of obstacle
 Serial.print("Distance : ");

distance formula we disused is use here.

Serial output

Open serial monitor, you will get distance somthing like this.

Leave a Comment