Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
please find the attached file
// C++ code
//Project 2 - Measuring the distance of an object using ultrasonic sensor
//and also smoothen the sensor data using moving average filter
int signal = 8;
void setup() {
// initialize serial communication between arduino and serial monitor
Serial.begin(9600);
}
void loop()
{
// in inches and centimeters:
float duration, inches, cm;
// signal is triggered by a HIGH pulse
// Given a short LOW pulse before to ensure a clean HIGH pulse:
pinMode(signal, OUTPUT);
digitalWrite(signal, LOW);
delayMicroseconds(2);
digitalWrite(signal, HIGH);
delayMicroseconds(10);
// Given a short LOW pulse
digitalWrite(signal, LOW);
// The same pin is used to read the signal from the signal pin a HIGH pulse
// whose duration is the time (in microseconds)
// to receive signal of its echo off of an object.
pinMode(signal, INPUT); //set signsl pin as input to get echo signal
duration = pulseIn(signal, HIGH); // set signal as HIGH to get output in microseconds by using pulseIn function
delay(1000); //wait for 1000 milliseconds
// convert the time into a distance
//distance =speed*time
//speed of sound in air at 20c degree temp =343m/s
//to change speed of sound to centimeter/microseconds
//meter - centimeter = 100, seconds to microseconds = 1000000
//speed of sound =0.0343 cm/ms
//centimeter to inches=0.393701
//speed of sound =0.0135 inch/ms
float distance_inch,distance_cm;
distance_inch=(duration*0.0135)/2; //divide by because time taken transmit and also receive signal
distance_cm=(duration*0.0343)/2;
Serial.print("distance:");
Serial.print(distance_inch);
Serial.print("in - ");
Serial.print(distance_cm);
Serial.println("cm");
float avg_inch=average(distance_inch); //average function called to get average value of distance in inches
float avg_cm=average(distance_cm); //average function called to get average value of distance in cm
Serial.print("average_distance:");
Serial.print(avg_inch);
Serial.print("in - ");
Serial.print(avg_cm);
Serial.println("cm");
delay(300); //wait for 300 milliseconds
}
long average(float value) // average function take average of 10 sample return average value
{
float avg[10];
int i;
int sample=10;
int sum=0;
for(i=0;i<sample;i++) // take 10 sample to average for it
{
avg[i]=value; // store 10 sample in array avg
sum +=avg[i]; // sum of all 10 sample values
}
float avg_value=sum/sample; // divide sample value to get average value
return avg_value; // return average value.
}