## Arduino and HC-SR04 ultrasonic sensor

10 september 2011 | Classified in: Electronic | Tags: Arduino, Ultrasonic, Sensor, HC-SR04, US-100

Here is just a simple code example.

### Code:

``````
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
*/

#define trigPin 12
#define echoPin 13

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

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
``````

### The Theory Behind It:

In the program above, we want to calculate the distance of an object in front of the ultrasonic sensor. This sensor can send a "ping" at a given moment and receive the ping bouncing back on an object at another given moment.
A ping is nothing but a sound that is inaudible for the human hear and this is why this sensor is called "ultrasonic".
The sensor send a ping at a time t1 and receive the bouncing ping at a time t2.
Knowing the speed of sound, the time difference Δt = t2 - t1 can give us an idea of the distance of an object.

Example, if Δt = 500 microseconds, we know it took 250 microseconds for the ping to hit an object and another 250 microseconds to come back.
The approximate speed of sound in dry air is given by the formula:
c = 331.5 + 0.6 * [air temperature in degrees Celsius]
At 20°C, c = 331.5 + 0.6 * 20 = 343.5 m/s
If we convert the speed in centimetres per microseconds we get:
c = 343.5 * 100 / 1000000 = 0.03435 cm/ųs
The distance is therefore, D = (Δt/2) * c
or D = 250 * 0.03435 = 8.6 cm

Instead of using the Speed of Sound, we can also use the "Pace of Sound".
The Pace of Sound = 1 / Speed of Sound = 1 / 0.03435 = 29.1 ųs/cm
In this case the equation to calculate the distance become: D = (Δt/2) / Pace of sound
and for the example above: D = 250 / 29.1 = 8.6 cm