Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
const int pin =2;//seting pin 2 as signal pin
long sum =0;//declaring all the global variable
long avg;
void setup()
{
Serial.begin(9600);
}
void loop()
{
long time ,inch ,cm;
long result;
pinMode(pin,OUTPUT);//makeing pin 2 as output
digitalWrite(pin,LOW);//making low for some time
delayMicroseconds(2);
digitalWrite(pin,HIGH);//making that pin has high
delayMicroseconds(2);
digitalWrite(pin,LOW);//making it has low
pinMode(pin,INPUT);
time=pulseIn(pin,HIGH);//getting the retrun wave noted in the time
//result=conversion(time);//calling the function
cm=(time/2)/29;//value from function part are calculated for the CM
inch=(time/2)/74;//value from function part are calculated for the Inches
Serial.println("inch");
Serial.println(inch);
Serial.println("cm");
Serial.println(cm);
delay(500);
}
//The sensor data is smoothened by using Moving average filter technique to eliminate the high frequency variations from the sensor data
// Moving average filter code
long conversion( long time)
{
int a[5];//intializing the variable
int i;
for(i=0;i<5;i++)
{
a[i] = time;//storing the value in array upto window size as 5
i++;
}
for(i=0;i<5;i++)
{
sum=sum+a[i];
}
return avg=sum/5; //returning that value
}