Challenge

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

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:

  • 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.
  • Measuring Pulse width using Input Capture Mode

Deliverables of this project:

  • The distance travelled by a wave to the object for which we want to measure the distance using Ultrasonic Distance Sensor (HC-SR04).
  • Measuring Pulse width using Input Capture Mode of Timer 1

Expected Outcomes:

The students will get the Knowledge on Ultrasonic sensor (HC-SR04) to measure the distance travelled by wave to the object, the hardware connection of Atmega328p and HC-SR04 and how to use input capture mode of Timer1

SOLUTION

//* P2: Measure Distance using Ultrasonic Distance Sensor *//

// Master code//

#include <Wire.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(2,3,4,5,6,7);

int Distance;

void setup()

{

Wire.begin();

Serial.begin(9600);

}

void loop()

{

Wire.requestFrom(8,1);

if (Wire.available()) {

Distance=Wire.read()

lcd.setCursor(0,0);

lcd.print("Distace= ");

lcd.print(Distance);

lcd.print("inch");

Serial.println(Distance);

delay(50);

Wire.end();

}

//* P2: Measure Distance using Ultrasonic Distance Sensor *//

// Slave Code//

#include <Wire.h>

#include <LiquidCrystal.h>

int Signal=2; // Change this pin according to setup//

LiquidCrystal lcd(2,3,4,5,6,7);

int Value,Duration;

void setup()

{

Wire.begin(8);

Serial.begin(9600);

Wire.onRequest(Distance);

}

void loop()

{

delay(100);

}

void Distance()

{

int count=0;

int TotalValue=0, AvgValue,Value=0;

int Arr[5];

while(count<5)

{

pinMode(Signal,OUTPUT);

digitalWrite(Signal,LOW);

delay(5);

digitalWrite(Signal,HIGH);

delay(10);

digitalWrite(Signal,LOW);

pinMode(Signal,INPUT);

Duration=pulseIn(Signal,HIGH);

Value=(Duration/74)/2;

Serial.println(Value);

Arr[count]=Value;

count+=1;

}

for(int i=0;i<5>

{

TotalValue+=Arr[i];

}

AvgValue=TotalValue/count;

Wire.write(AvgValue);

delay(10);

}

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.