### 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.

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 :

Use this sketch :

const int trig = 2; const int ech = 3; void setup() { pinMode(trig, OUTPUT); pinMode(ech, INPUT); Serial.begin(9600); } void loop() { digitalWrite(trig, LOW); delayMicroseconds(2); digitalWrite(trig, HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); long timeRequied = pulseIn(ech, HIGH); //measure time required int distance = (timeRequied / 2) / 29.1; //calculate the distance Serial.println(distance); delay(1000); }

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