Challenge

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

AIM: Measuring the distance using an ultrasonic sensor

void US_Tx();
unsigned int US_Rx();
float mov_Avg();
float MicroToinches(float);
void setup()
{
Serial.begin(9600);
}

void loop()
{
float Time = mov_Avg();
float distance = MicroToinches(Time);
Serial.print(distance);
Serial.println();
}
void US_Tx()
{
pinMode(7,OUTPUT);

digitalWrite(7,LOW);
delayMicroseconds(2);

digitalWrite(7,HIGH);
delayMicroseconds(5);

digitalWrite(7,LOW);
delayMicroseconds(2);
}

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)
{
float inches=D/73.35/2;
return inches;
}

float mov_Avg()
{
int window_size =5;
int data[window_size];
US_Tx();
data[0]=US_Rx();
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;
return filterValue;

}

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.