Challenge

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

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

#include<LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int trigPin = 11; // Trigger pin
int echoPin = 12; // Echo pin
long duration, distance, inches;
long sum=0;
long avg;
int i;

void setup()

{
lcd.begin(16, 2);
Serial.begin (9600); //Serial Port begin
pinMode(trigPin, OUTPUT);//Define inputs and outputs
pinMode(echoPin, INPUT);
}

void loop()

{

digitalWrite(trigPin, LOW);
delay(00);
digitalWrite(trigPin, HIGH);
delay(500);
digitalWrite(trigPin, LOW);


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

// Convert the time into a distance

distance = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
inches = (duration/2) / 74; // Divide by 74 or multiply by 0.0135
for (i=0; i<5; i++)
{
sum=sum+inches;
avg = sum/5;
}
if (distance >= 335 || distance <= 0)
{
Serial.println("Out of range");
lcd.setCursor(0,0);
lcd.print("Out of range");
delay(250);
lcd.clear();
}

else
{
Serial.print(distance);
Serial.print("cm ,");
Serial.print(avg);
Serial.print("Avg ");
Serial.println();
Serial.print(inches);
Serial.print("inches");
Serial.println();
lcd.setCursor(0,0);
lcd.print("distance in cm");
lcd.setCursor(0,1);
lcd.print(distance);

}
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.