Using the HC-SR04 Sensor with Ardiuno for Obstacle Detection and Distance Measurement
Goal:
We are going to use HC-SR04, an ultrasonic sonar with Arduino to detect an obstacle and measure the distance of the obstacle.
Required Hardware:
For this project, we need –
- Arduino Uno
- Ultrasonic Sonar – HC-SR04
What is Ultrasonic Sonar?
SONAR stands for SOund Navigation And Ranging.
Sonar is a technique that uses sound propagation to navigate, communicate with or detect objects on or under the surface of the water, such as other vessels. Two types of technology share the name “sonar”:
- Passive sonar is essentially listening for the sound made by vessels;
- Active sonar is emitting pulses of sounds and listening for echoes.
The device, HC-SR04 that we are going to use for this project is an active sonar module.
How does the HC-SRO4 Ultrasonic Sonar Module Work?
The module starts by sending eight 40 kHz, 10 microseconds long signals. The module then tries to detect whether there is a pulse back signal. If the module receives back a signal, time of high output IO duration is the time from sending ultrasonic to return back to the module.
Test distance = (Total duration / 2) * speed of sound
Note that, the velocity of sound at 30-degree Celcius temperature is 350 meters per second.
We divide the total travelled distance of the signals by 2 because the signal takes equal time to travel to the obstacle and to come back to the sensor from the obstacle. So, we divide the total time by 2, to only consider the time taken for the signal to reach the obstacle or the time taken to come back from it.
Pin Out:
- VCC – You need to supply 5V through this pin
- GND – This pin should be connected to the ground
- Trig – You only need to supply a short 10uS pulse
- Echo – Receive incoming signal through this pin
Schematic:
Code:
// defines pins numbers int trigPin = 10; int echoPin = 11; // defines variables long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication } void loop() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); // trigPin to HIGH delayMicroseconds(10); // Wait 10 micro seconds digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // Reads the echoPin // Calculating the distance distance = duration * 0.035/2; // Prints the distance on the Serial Monitor Serial.print("Distance: "); Serial.println(distance); }
Now, upload the code to your Arduino, open the serial monitor and aim the sonar at your nearest wall. You should see the serial monitor display the distance between the Sonar and the wall.