Arduino with HCSR04 Ultrasonic sensor


Connect ultrasonic sensor HCSR04 to Arduino and print distance data on our serial port

Working of HCSR04

It has two eyes, one sends out ultrasonic signals and other eye receives ultrasonoic signals, We calcualte the time difference between transmission and reception and use simple formula, Distance = Speed*Time to calculate distance of object infront of the sensor .

Resources needed

SNo Component Quantity
1 Arduino uno 1
2 HCSR04 Ultrasonic sensor 1
3 Jumper wire 4
4 Breadboard 1


cod screen shot


#define trigPin 4
#define echoPin 2
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

Below is the copy of working code

cod screen shot

Code Explanation

We connect our ultrasonic sensor trig and echo pins to digital pins 4 and 2 of our Arduino respectively and define those pins as trigPin and echoPin in our code above our setup function. Within our setup() function we do one time initialization to begin our serial transmission @baudrate of 9600, trigPin as OUTPUT and echoPin as INPUT.

Next we define our variables, duration and distance as long datatype. We make our trigPin high which will send out ultrasonic signals and we calculate the time taken for receiving the sent out signal using pulseIn() function and do the necessary math to calculate the distance from constant value of speed of sound in air.