In this tutorial we learn how to measure the distance by using Ultrasonic Sensor with Arduino. Get their pin connections, circuit diagram with code/sketch and Output.

»Read more about Ultrasonic sensor

Components List

  Ultrasonic Sensor (HC-SR04)
  Arduino Uno
  Jumper Wires

Pin Connections

Ultrasonic Pins Arduino Pins 
5v or Vin 5V
GND GND
Trigger 9
Echo 8

Circuit Diagram of Ultrasonic Sensor With Arduino

Circuit Diagram of Ultrasonic Sensor With Arduino

Code for Ultrasonic Sensor with Arduino

int trigPin = 9; // Trigger Pin of Ultrasonic Sensor
int echoPin = 8; // Echo Pin of Ultrasonic Sensor

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

}

void loop(){
  long duration, inches, cm;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);

  inches = duration/74 /2;  //convert microseconds into inches
  cm = duration/29 /2;		//convert microseconds into cm
  
  Serial.print(inches);
  Serial.print(" inches ");
  Serial.print(cm);
  Serial.print(" cm");
  Serial.println();
  delay(200);
}

Output of Ultrasonic Sensor with Arduino

Output of Ultrasonic Sensor with Arduino

Our Youtube Channel