how HC-SR04 ultrasonic works

HC-SR04 ultrasonic sensor with arduino tutorial

Little Theory about HC-SR04 – How Ultrasonic sensor works

HC-SR04 is a distance sensor based on ultrasonic. Distance obtained by calculating how much time required for ultrasonic to travel from transmitter to receiver. In the beginning, ultrasonic wave transmitted from a transmitter sensor and reach an obstacle. When ultrasonic wave reach obstacle, the wave will bounce back to sensor at receiver.

how HC-SR04 ultrasonic works
how HC-SR04 ultrasonic works

If we knew the speed of ultrasonic, then will obtain the distance by measure time required for wave to bounce back. We remember that distance is speed multiply time. Which is :

S = V * t

We want obtain distance from sensor to obstacle, so we need to divide the distance by 2. So it turn into

S = (V * t) / 2

Ultrasonic is sound wave, so we already knew that the speed of sound is 340m/s. Then let arduino measure time required by ultrasonic to bounce back to sensor.  Say that time required is 100 uS. So the distance will be :

S = (340*100^-6)/2

S = 0,017m or 1,7cm

or you can simplify the formula into :

S = t/2/29.1

Apply the theory – Use HC-SR04 ultrasonics sensor with arduino

When we need distance sensor for our project, HC-SR04 can be the answer. HC-SR04 is very simple and cheap distance sensor. Now we will examine how to use this simple sensor.

Follow schematic below :

HC-SR04 arduino
HC-SR04 arduino

Use this sketch :

const int trig = 2;
const int ech = 3;

void setup() {
  pinMode(trig, OUTPUT);
  pinMode(ech, INPUT);

void loop() {
  digitalWrite(trig, LOW);
  digitalWrite(trig, HIGH);
  digitalWrite(trig, LOW);
  long timeRequied = pulseIn(ech, HIGH); //measure time required
  int distance = (timeRequied / 2) / 29.1; //calculate the distance

The sketch above will display distance measured by sensor in Serial Monitor.

One Reply to “HC-SR04 ultrasonic sensor with arduino tutorial”

  1. Dear Sir,

    I want to make solar road stud using 6 Volts 100 mA Solar Panel + 4.2 V-2200 mAh Li-ion battery and a protection circuit for over charging and under voltage cut off. Could you provide me the circuit diagram?

    Please also send me online tutorial course contents and fee structure.

    Thanking in anticipation,


Leave a Reply

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