Ultrasonic sensor distance measurement

HC-SR04 UltraSonic Sensor distance
This post describes the use of an ultrasonic sensor to measure distance of a target. The goal of this post is to help you understand how this sensor works and then you can use this example in your own projects, such as detecting a wall or measuring the water level in a water tank.
These days, you can pick up an ultrasonic sensor for a couple of £. We decided to buy a HC-SR04 sensor from eBay for £1.62.
This sensor is really cool and popular among hobbyists and tinkerers.
The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object, with excellent accuracy. It can detect objects from 2cm to 400 cm away and it comes in an easy-to-use package, consisting of ultrasonic transmitter and receiver.


  • Power Supply :+5V DC
  • Working Current: 15mA
  • Effectual Angle: <15°
  • Ranging Distance : 2cm – 400 cm
  • Resolution : 0.3 cm
  • Measuring Angle: 30 degree
  • Trigger Input Pulse width: 10uS


  • VCC: +5VDC
  • Trig : Trigger (INPUT)
  • Echo: Echo (OUTPUT)
  • GND: GND


HC-SR04 Connection
HC-SR04 Connection to Arcuino


#define trigPin 3
#define echoPin 2
// BehindTheSciences.com

void setup() {

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


void loop() {

long duration, distance;
digitalWrite(trigPin, LOW);  // Set trigger Pin to Low
delayMicroseconds(2); // Delay for 2 microseconds
digitalWrite(trigPin, HIGH); // Set trigger Pin to Low
delayMicroseconds(10); //
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distance = ((duration/2) / 29.1);

if (distance >= 400 || distance <= 0)
   Serial.println("Out of range");
   Serial.println(" cm");

Upload the code to your Arduino and Open terminal; you should start seeing reading flying on your screen!
HC-SR04 terminal
HC-SR04 Arduino terminal
Send us comments and suggestions at contact@

Add a Comment

Your email address will not be published. Required fields are marked *