Challenge

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

Offline

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

Program:

// Measuring the distance using ultrasonic sensor

void US_Tx();
unsigned int US_Rx();
float mov_Avg();
float MicroToinches(float);


void setup()
{
Serial.begin(9600); //begin serial communication at 9600 baud rate
}

void loop()
{
float Time=mov_Avg();
float distance = MicroToinches(Time); //to find distance converting time microseconds into inches
Serial.print(distance); //to print distance in serial monitor
Serial.println();
}
void US_Tx() //Generating the pulses
{
pinMode(7,OUTPUT); //set pin 7 as output value

digitalWrite(7,LOW); //pin 7 equal to low state
delayMicroseconds(2); //delay for 2 microseconds

digitalWrite(7,HIGH); //pin 7 equal to high state
delayMicroseconds(5); //delay for 5 microseconds

digitalWrite(7,LOW); //pin 7 equal to low state
delayMicroseconds(2); //delay for 2 microseconds
}

unsigned int US_Rx()
{
pinMode(7,INPUT);
unsigned int Duration = pulseIn(7, HIGH);
return Duration; //how much duration pin is high in Ms

}

float MicroToinches(float D) //calling the duration value
{
float inches=D/73.35/2; //convert duration into inches
return inches; //return the value
}

float mov_Avg()
{
int window_size =5; //declaring window size
int data[window_size];
US_Tx(); //Triggering the data
data[0]=US_Rx(); //Receiving the data
US_Tx();
data[1]=US_Rx();
US_Tx();
data[2]=US_Rx();
US_Tx();
data[3]=US_Rx();
US_Tx();
data[4]=US_Rx();


float filterValue = (data[0]+ data[1]+data[2]+data[3]+data[4])/window_size; //To find moving average value
return filterValue;

}

Output:

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.