Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#include<LiquidCrystal.h>
//header file for lcd
LiquidCrystal lcd(13,12,8,9,10,11);
//pin configuration
int inches = 0;
int cm = 0;
int range=10,index=0;
float val[10];
int avarage,con=0;
float cValue;
//variable declartion for filter
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
}
void loop()
{
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance( 7,7);
// convert to inches by dividing by 2.54
inches = (cm / 2.54);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("inch:");
lcd.print(inches);
lcd.setCursor(0,1);
lcd.print("cm:");
lcd.print(cm);
//printing statements
delay(100); // Wait for 100 millisecond(s)
cValue=readUltrasonicDistance(7,7);
con=con-val[index];
val[index]=cValue;
con=con+val[index];
index=index+1;
if(index>=range)
{
index=0;
}
avarage=con/range;
//logic for moving filter
Serial.print("\nAvarage:");
Serial.print(avarage);
}