How to interface HC-SR04 Ultrasonic Sensor with Arduino

About:

HC-SR04 is an Ultrasonic sensor module which includes ultrasonic transmitter, receiver and control circuit in one small PCB.  HC-SR04 has distance measurement ability ranging from 2cm to 400cm. These small units are very accurate and its ranging accuracy can be reach to 3mm.




How HC-SR04 Works:

Ultrasonic modules work on principle similar to radar or sonar. It generates high frequency signal of 40kHz towards object and receives echo signal from subjects surface. Then it can calculate object distance using time interval between the sending of signal and the receiving of echo.




Theory:

To measure the object distance form sensor body we need to send a trigger pulse of 10uS, module will detect the trigger and will send out one 8cycle ultrasonic sound bust of 40kHz towards subject and receives echo of transmitted signal from objects surface. Now you can calculate distance from time interval between sending of signal and receiving of signal.

Distance Calculation:

Time=distance/speed

t = s / v

s = t . v

Speed of sound is 340m/s

v=340m/s = 0.034cm/uS

So, in order to calculate distance in cm, we need to multiply time with 0.034. But in this case time is distance between sensor and object in one way only and in our case the time value we will get from echo will be double because the sound wave needs to travel towards objects and bounce back to sensor. So, in our case the formula will be,

s = t . v/2

s = t . 0.034/2

Circuit Diagram:

Circuit Diagraam

Basic Code:

/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* Crated by Pranay Sawarkar,
* www.eTechPath.com
*
*/
// defines arduino pin numbers
const int trigPin = 9;
const int echoPin = 8;
// 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);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}







Leave a Reply

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