Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
OFFLINE
float microsecToinchs( float d);//initialize the function to global
float avg;//initialize the global
int i,sum;//initialize the global
int duration,inches;//initialize the global
float Duration_inch;//initialize the global
int data[5];//initialize the global
void setup()
{
Serial.begin(9600);//to view serial monitor
pinMode(7, INPUT);//the input pin at 7
}
void loop()
{
float average = mov_avg();
Serial.println("distance value is");//to display the distance value of serial monitor
Serial.println( inches);
delay(1000);//delay in 1 sec
}
void US_Tx()//function definition for transmission
{
pinMode(7,OUTPUT);//the output pin at 7
digitalWrite(7,LOW);//to set the ouput in low
delayMicroseconds(2);//delay in microsec 2
digitalWrite(7,HIGH);//to set the ouput in high
delayMicroseconds(5);//delay in microsec 5
digitalWrite(7,LOW);//to set the ouput in low
delayMicroseconds(2);//delay in microsec 2
}
float US_Rx()//function definition for receiver
{
pinMode(7,INPUT);//the input pin at 7
duration=(unsigned int)pulseIn(7,HIGH);//to receive the pulse
Duration_inch = microsecToinchs(duration);
return Duration_inch;//to rerturn the duration inch
}
float microsecToinchs(float d)//function definition for microsectoinchs
{
inches=((d/73.35)/2);//to calculate the inches value
return d;//to return d
}
float mov_avg()//function definition for moving average
{
for(i=0;i<5;i++)
{
US_Tx();//to call trasmission function
data[i]=US_Rx();//to call receiver function
sum=sum+data[i];//to calculate sum value
}
avg=sum/5;//to calculate average value
return avg;//to return average
}