Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
int triggerPin=7;
int echoPin=7;
float arr[10]={0};// array variable to take 10 samples of echo
float cur_avg=0;
float inches = 0;
float cm = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{//moving avarage filter take 10 samples and find the avarage
for(int i=0;i<10;i++)
{
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);
arr[i]= pulseIn(echoPin, HIGH);
}
float whole_sum=0;
for(int i=0;i<10;i++)
{
whole_sum+=arr[i];
}
cur_avg=whole_sum/10;
cm = 0.01723 * cur_avg;
inches = (cm / 2.54);
Serial.print(inches);
Serial.println("in, ");
Serial.print(cm);
Serial.println("cm");
}
