Challenge

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

In this project we have to Measure the distance of an object using ultrasonic sensor (HC-SR04)

We will be using a Ultrasonic Distance Sensor for our input sourse and we will be using ATMEGA328 microcontroller.

For circuit digram we will use ATMEGA328 microcontroller, whose input and output PIN we will configure according to our need.

Than we will give 5 volt supply to ultrasonic sensor with the help of potentiometer.

Then we will connect trigger to our output PIN and echo to input PIN.

Then we will connect oscope to see the Pulse width. To see the distance open serial monitor.

We are measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor.

Circuit Diagram

Code

int trigPin = 5; // Trigger
int echoPin = 6; // Echo
long duration, cm;

void setup()
{
//Serial Port begin
Serial.begin (9600);
//Define input and output PIN
pinMode(PD5, OUTPUT); // configured the output pin as PD5
pinMode(PD6, INPUT); // configured the input pin as PD5
}

void loop()
{

digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(15);
digitalWrite(trigPin, LOW);


pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

// Convert the time into a distance
cm = (duration/2) / 29; // Divide by 29 to convert m/s to cm

Serial.print(cm);
Serial.print("cm");
delay(250);
}

Output when we do not provide 5 V, Distance = 0cm

Output when we provide 5 V, Distance = 613cm

If you change the position of potentiometer then you will get the pulse width accordingly and also distance.

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.