Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
float inches = 0;
float cm = 0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
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);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
int window[10]={0};
void setup()
{
Serial.begin(9600);
}
void loop()
{
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7, 7);
// convert to inches by dividing by 2.54
inches = (cm / 2.54);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
delay(1000); // Wait for 1000 milliseconds(s)
int current_samp = 0;
current_samp = (cm); // duration = current_samp
delayMicroseconds(300); // taking delay
pushVal(current_samp); // calling function
Serial.print("Average data ");
Serial.println(takeAvg () ); // calling function
delay(1000); // Wait for 1000 millisecond(s)
}
void pushVal(int val)
{
int i = 0;
for(i = 1;i < 10; i++) // This for loop run for 10 time
{
window[i-1] = window[i]; // here setting window previous value as window new value
}
window[10 - 1] = val; // finally giving to val
}
int takeAvg() // this function is just taking simple avg of 10 element
{
int i = 0;
long sum = 0;
for(i = 0;i < 10; i++) // This for loop is adding 10 element
{
sum += window[i]; // in each cycle sum value is increasing
}
return (sum / 10); // dividing sum with number of element i.e. '10'.
}
Components used:
Arduino uno R3
Ultrasonic distance sensor Ping
Jumperwires