Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Arduino Code:
TinkerCad Plateform:
// C++ code
//
double filter_values[5] = {0,0,0,0,0}; //Initialize array of length 5 to store the previous sensor data to calculate the moving average value
int current_array_pos = 0; //Initialize current arrary position variable as 0
void setup()
{
Serial.begin(9600); //Start Serial UART connection with Baud Rate of 9600
}
void loop()
{
double duration = 0,smooth_average_value=0; //Initialize variables as doubles to store precise values
double inch=0;
pinMode(7,OUTPUT); //Send a high pulse to PING28015 to get data
digitalWrite(7,LOW); //To send data first, initialize pin 7 as OUTPUT
delay(10);
digitalWrite(7,HIGH);
delay(2);
digitalWrite(7,LOW);
pinMode(7,INPUT); //Reinitialize pin 7 as Input and capture the duration of HIGH Pulse
duration = pulseIn(7, HIGH); //PulsIn command is used to find the duration of the HIGH Pulse send from the ultrasonic Sensor
smooth_average_value = smoothValue(duration); //Send the duration value to moving average function to smooth the received duration data
inch = (smooth_average_value/2)/74; //Calculate inches from the duration. Sound travels 13.5 inches per microsecond. So 74.07 microseconds per inch.
Serial.print("Distance of the Object (in inches): "); //Print the inches value on the Serial Port
Serial.println(inch);
}
double smoothValue(double value) //This function is used to smooth the values of the sensor by moving average method
{
double average=0; //Initialize an average value variable
double total_filter_values = 0;
if (current_array_pos!=5) //Check whether the array is filled. If not then add the value to the array
{
filter_values[current_array_pos] = value;
current_array_pos += 1;
}
else //Else, delete 0th element and left shift the array values and add the new value to the last element of the array
{
for(int i=0;i<4;i++)
{
filter_values[i] = filter_values[i+1];
} //This loop is used to shift the values to the left
filter_values[4] = value; //Add the new sensor value
}
for(int i=0;i<5;i++)
{
total_filter_values += filter_values[i];
} //Calculate the total value of the sensor data
Serial.print("Filter array: "); //Printing the array elements for debugging and understanding purposes
for(int i=0;i<5;i++)
{
Serial.print(filter_values[i]);
Serial.print(" ");
}
average = total_filter_values/current_array_pos; //Caluculate the average value
return average; //Return the average value to the main function for further calculations
}
TinkerCad Link: https://www.tinkercad.com/things/25zmpS67DDN?sharecode=dZa5lnF3QPbheO_bjleRbGKBpPDzG82DspS7lRdadas