electroSome

Interfacing Ultrasonic Sensor with Arduino Uno

HC-SR04 Ultrasonic Sensor

HC-SR04 Ultrasonic Sensor

In this tutorial we will learn about integrating HC-SR04 ultrasonic distance sensor with Arduino Uno. Ultrasonic sensors are commonly used for obstacle detection and distance measuring applications. The sensor works on the same principles of a radar system, which converts electrical energy into acoustic waves and vice versa. The HC-SR04 ultrasonic sensor is based on the principle of SONAR, which is an abbreviation of Sound Navigation Ranging. This sensor is used in many hobby projects where there is a need for obstacle detection or distance measurement.

Components Required

HC-SR04 Ultrasonic Sensor

Features

Working

The functionality of the HC-SR04 ultrasonic sensor can be initiated by giving a 10μS HIGH level signal on the TRIGGER input pin. Then the module will send out eight ultrasonic burst of 40KHz. These ultrasonic sound waves travels through the air and if it finds an object or obstacle on its path then it will automatically reflect or bounce back to the receiver of the module. If the module detects signal back, it will send out a HIGH pulse in ECHO pin for the duration equivalent to the time taken for the ultrasonic waves to come back. Now the distance of the obstacle can be calculated by using the this time duration.

Distance Calculation

Circuit Diagram

Integrating HC-SR04 Ultrasonic Distance Sensor Arduino Uno – Circuit Diagram

Description

Program

// defines pins numbers
const int trigPin = 2;
const int echoPin = 6;

// 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 the 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.0343/2;
    // Prints the distance on the Serial Monitor
    Serial.print(“Distance: “);
    Serial.println(distance);
}

Code Explanation

Output

Conclusion

Hope you understand about HC-SR04 ultrasonic distance sensor and how to interface it with Arduino Uno. Feel free to modify above code as per your applications. For any doubts, comment box is always open for you below.