Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
#define WINDOW_SIZE 5 //defining macro WINDOW_SIZE as 5
int cm = 0; //initialising variable to store the received distance in cm
int inches = 0; //intialising variable to store distance in inches
int Data = 0;
int Total = 0;
int Average = 0;
int Reading[WINDOW_SIZE]; //intialising the array to store consequent readings
int index = 0; //variable for accessing array elements
//function for triggering the signal pin of Ultrasonic distance sensor as triggerpin and echopin with aurdino PIN
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin,OUTPUT); //setting triggerPin as output
digitalWrite(triggerPin,LOW); //setting triggerpin as low
delay(100);
digitalWrite(triggerPin,HIGH); //setting triggerpin as high
delay(100);
digitalWrite(triggerPin,LOW); //setting triggerpin as low
pinMode(echoPin,INPUT); //setting echoPin as input
return pulseIn(echoPin,HIGH); //setting echopin as high
}
void setup()
{
Serial.begin(9600); //initiating serial communication
}
void loop()
{
cm = 0.01723*readUltrasonicDistance(7,7); //calling fun and getting distace and multiplying it with its multiplication factor from datasheet
inches = (cm/2.54); //converting cm to inches
Total -= Reading[index]; //removing old enteries from total
Data = inches;
Reading[index] = Data; //adding newest reading to array
Total += Data; //adding newest data to total
index = (index+1) % WINDOW_SIZE; //incrementing the inex, and setting in to 0 when is exceeds the window size
Average = Total / WINDOW_SIZE; //diving total with window size
Serial.print("Distance DATA is "); //printing the distance
Serial.println(inches);
Serial.print("Smoothened DATA is ");
Serial.println(Average*100);
delay(100);
}