Challenge

Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)

Overview of the Project: 

In this project, the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04).

Goals:

  • Implement code to interface HC-SR04 ultrasonic sensor with Atmega328p
  • Measuring the distance of an object using Ultrasonic Distance Sensor (HC-SR04)
  • Usage of Input Capture Mode

Key Highlights of the Project: 

  • Measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor.

Circuit: 

Program: 

#define echo 8 //defining macros at pin-8 echo pulse
#define trig 9 //defining macro at pin-9 triggering

long duration; //declaration of global variable duration with long data type
int distance; //declaration of global variable distance with long data type

void setup() {
pinMode (trig, OUTPUT); //setting trig pin as output
pinMode (echo, INPUT); //setting echo pin as input

Serial.begin(9600); 
}

void loop() {
digitalWrite(trig, LOW); //clear the output pin
delayMicroseconds (2); //wait for 2microsec
digitalWrite(trig, HIGH); //setting output pin to High
delayMicroseconds (10); //delay of 10microsec
digitalWrite(trig, LOW); //clear the output pin
duration = pulseIn (echo, HIGH); //Returning time in microsec
distance = duration*0.034/2; //formula used distance=(sound_speed*time)/2. where time=pulse duration=10microsec and sound_speed=340m/s=0.034cm/microsec.
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" centimeter");

}

Simulation and Results:

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.