Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

#include<Liquidcrystal.h> //library for LCD display
LiquidCrystal lcd(2,7,8,9,10,11); //Initialize the LCD display
float time=0,distance=0,inches = 0;
long sum = 0;
long avg;
const int pingPin = 4; //Declaring Pin 4 has a output pin
void setup()
{
Serial.begin(9600); //Initialize serial communication
lcd.begin(16,2);
lcd.print("Ultra sonic");
lcd.setCursor(0,1);
lcd.print("Distance Meter");
delay(2000);
lcd.clear();
}
void loop()
{
lcd.clear();
pinMode(pingPin,OUTPUT); // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. digitalWrite(pingPin,LOW);// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
delayMicroseconds(2);
digitalWrite(pingPin,HIGH);
delayMicroseconds(2);
digitalWrite(pingPin,LOW);
delayMicroseconds(2);

pinMode(pingPin,INPUT);// The same pin is used to read the signal from the PING
time = pulseIn(pingPin,HIGH); // a HIGH pulse whose duration is the time (in microseconds) from the sending of the ping
// to the reception of its echo off of an object.


distance=time*.034/2;
inches = distance/2.54;
for(int i = 0;i < 5;i++)
{
sum = sum+inches;
avg = sum/5;
}
Serial.print("Average: ");
Serial.print(avg);
Serial.println();
lcd.clear();
lcd.print("Distance:");
lcd.print(distance);
lcd.print("cm");
lcd.setCursor(0,1);
lcd.print("Inches:");
lcd.print(inches);
lcd.print("in");
delay(1000);
}

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.