Interface a HC-SR04 Ultrasonic Ranging Module with Arduino

What is the HC-SR04 Ultrasonic sensor?

It is an ultrasound-based sensor used for detecting an object and measuring the distance between the object and the sensor. It consists of an ultrasonic transmitter and a receiver. The transmitter transmits an ultrasonic wave that is not audible to human ears. The transmitted wave then gets reflected back by the object and received by the receiver. After calculating the time between the received and transmitted wave we can easily calculate the distance of the object. As we already know the speed of sound and time taken by the wave we can now easily use the formula speed=distance/time and calculate the distance of the object.    

Pin configuration of the HC-SR04 Ultrasonic Ranging Module

ultrasonic sensor pin diagram

Features of the HC-SR04 Ultrasonic Ranging Module

  • The operating voltage is 5 volts.
  • The current consumption is 15mA.
  • The operating frequency is 40KHz.
  • It can measure a distance between 2-400cm.
  • Its measuring angle is 15°. 

Components needed

  • Arduino UNO
  • HC-SR04 Ultrasonic Ranging Module
  • Jumper wires
  • Breadboard

Pin connections of  the HC-SR04 Ultrasonic Ranging Module with Arduino UNO

  • Connect the VCC pin of the module to the 5-volt pin of the Arduino UNO.
  • Connect the GND pin of the module to the GND pin of the Arduino UNO.
  • Connect the Trig pin of the module to the D2 pin of the Arduino UNO.
  • Connect the Echo pin of the module to the D3 pin of the Arduino UNO.

Circuit diagram of the HC-SR04 Ultrasonic Ranging Module with Arduino UNO

ultrasonic sensor circuit diagram

Arduino code for the HC-SR04 Ultrasonic Ranging Module

const int trigPin = 2;// Define the trig pin of the module
const int echoPin = 3;// Define the echo pin of the module
 
long t;// Create a variable to store the time
int dist; // Create a variable to store the distance
void setup() {
  Serial.begin(9600); // Set baud rate for serial communication
pinMode(trigPin, OUTPUT);// Set trig pin as OUTPUT
pinMode(echoPin, INPUT);// Set echo pin as INPUT
 
}
void loop() {
 
digitalWrite(trigPin, LOW);// Set trig pin as LOW to clear the pin
delayMicroseconds(2);// Give a delay of 2ms
digitalWrite(trigPin, HIGH);// Set trig pin as HIGH 
delayMicroseconds(10); // Give a delay of 10ms
digitalWrite(trigPin, LOW);// Set trig pin as LOW
t= pulseIn(echoPin, HIGH);// Get the value of time from the module using pulseIn() function
dist=t*0.034/2;// Calculate distance using the formula Speed=Distance/Time
Serial.print("Distance of object: ");
Serial.println(dist);// Print the distance on the serial monitor
}

Leave a Reply