How To Interface Ultrasonic sensor and measure distance

Hi, I am Somu Ghosh . Today i am going to teaching how to interface ultrasonic sensor with arduino and measure distance.

Let's start.......

First of all we need to know about ultrasonic sensor . ( Go to modules and sensors section )

Equipment that we need :

  1. Arduino Uno.
  2. Sets of Jumper wire .
  3. Breadboard . ( If necessary or not)
  4. HC-SR04 Ultrasonic sensor .
  5. Arduino IDE . ( For Programming )

Follow the circuit diagram and connect the wires.

Ultrasonic sensor diagram


#define echoPin 2                   // attach pin Digital 2 Arduino to pin Echo of HC-SR04
#define trigPin 3                    //attach pin Digital 3 Arduino to pin Trig of HC-SR04

// defines variables
char value;
long duration;                             // variable for the duration of sound wave travel
int distance;                            // variable for the distance measurement

void setup() {
pinMode(trigPin, OUTPUT);                   // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT);                   // Sets the echoPin as an INPUT
Serial.begin(9600);                     // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test");              // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
void loop() {

// Clears the trigPin condition

digitalWrite(trigPin, LOW);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds

digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);

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

duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;         // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(" cm");